RainbowJeremy
RainbowJeremy

Reputation: 73

Changing Color of Buttons

My application has four buttons. I am trying to have the color of the buttons change to one color if they are pressed in a certain order and have them change to a different color if they are pressed in a different order. Right now my code is this:

public class MainActivity extends Activity {

int b1 = (int) (Math.random() * 10.0);
int b2 = (int) (Math.random() * 10.0);
int b3 = (int) (Math.random() * 10.0);
int b4 = (int) (Math.random() * 10.0);
int last = 0;
int[] nums = { b1, b2, b3, b4 };
int i = 0;
String res = "";
Button button1 = (Button) findViewById(R.id.button1);
Button button2 = (Button) findViewById(R.id.button2);
Button button3 = (Button) findViewById(R.id.button3);
Button button4 = (Button) findViewById(R.id.button4);

private void checkOrder(int value) {
    if (value == nums[i]) {
        if (i == 3) {
            //DO SOMETHING ELSE
        } else {
            if(value==b1){
                button1.getBackground().setColorFilter(0xFF00FF00, PorterDuff.Mode.MULTIPLY);
            }else if(value==b2){
                button2.getBackground().setColorFilter(0xFF00FF00, PorterDuff.Mode.MULTIPLY);
            }else if(value==b3){
                button3.getBackground().setColorFilter(0xFF00FF00, PorterDuff.Mode.MULTIPLY);
            }else if(value==b4){
                button4.getBackground().setColorFilter(0xFF00FF00, PorterDuff.Mode.MULTIPLY);
            }
            i++;
        }
    } else {
        //DO SOMETHING ELSE
    }
}

Right now I am getting a NullPointerException where the buttons are created. I think this is because the buttons are not created in the onCreate method. However, if I do put the buttons in the onCreate method they cannot be accessed in the checkOrder method. How would I go about changing their colors from a different method? I know that similar questions have been asked in the past, but I have not found one with the same problem I am facing.

Upvotes: 1

Views: 132

Answers (1)

Darshil Shah
Darshil Shah

Reputation: 361

Declare your buttons at class level and initialize them in onCreate method

Class Demo extends Activity{

    Button button1,button2,button3,button4;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        button1 = (Button) findViewById(R.id.button1);
        button2 = (Button) findViewById(R.id.button2);
        button3 = (Button) findViewById(R.id.button3);
        button4 = (Button) findViewById(R.id.button4);
    }
}

After this use wherever you want to use

Upvotes: 3

Related Questions