Vigi
Vigi

Reputation: 177

setBackgroundDrawable works correctly; until another button is pressed, why?

In my app I have 4 main buttons, plus another 2. These 4 buttons are declared at the beginning of the main activity.

Button button1, button2, button3, button4;
button1 = (Button) findViewById(R.id.button1);
button1.setTag("blue");

(each button has a tag and is set the same way as button1)

The four buttons I want to cycle through different colours when they are pressed. I manage this by;

public void button1(View v) {

    if ("blue".equals(button1.getTag())) {
        button1.setBackgroundDrawable(getResources().getDrawable(
                R.drawable.brown));
        button1.setTag("brown");
    } else if ("brown".equals(button1.getTag())) {
        button1.setBackgroundDrawable(getResources().getDrawable(
                R.drawable.red));
        button1.setTag("red");
    } else if //...etc

This works all well and good until I press any of the two buttons, an example code of one of the buttons

    public void back(View v) {
    setContentView(R.layout.main);
    t = new TextView(this);
    t = (TextView) findViewById(R.id.textView1);
    t.setText("");
}

Once I press any of the two buttons the colours change back to the original drawable set in the xml file

android:background="@drawable/blue"

Now when I press the 4 main buttons the drawable does not change, but I definitely know that it is getting re-tagged, so why won't it change the drawable after I press the button?

Upvotes: 1

Views: 1726

Answers (1)

antonyt
antonyt

Reputation: 21883

If your 'two buttons' onClick handler makes a call to Activity.setContentView(int), then all of the buttons will reset to how they are specified in the original XML layout. New views will be inflated and these will not have a tag (you do not seem to be re-setting the tags after the call to setContentView). A null tag will not match any of your colour strings and so your buttons will not cycle their background.

If you want to maintain the views how they were, then do not reset the content view of the Activity. In most cases, setContentView is only called once per lifetime of an Activity, although obviously there can be a few exceptions.

Upvotes: 3

Related Questions