1

I have created a simple android app that allows the user to click a button and change the background color. However, after I rotate the device, the color changes back to the default. I have attempted to save my color in the onSavedInstanceState() method, but to no avail. See my code below

public class MainActivity extends Activity {

    Button button1;
    Button button2;
    LinearLayout background;
    private static String COLOR_VALUE;
    int mColor;

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

        background = (LinearLayout)findViewById(R.id.main);
        if (savedInstanceState != null){
            mColor = savedInstanceState.getInt(COLOR_VALUE);
        }

        button1 = (Button)findViewById(R.id.button1);
        button1.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                mColor = Color.parseColor("#ff0000");
                background.setBackgroundColor(mColor);
            }
        });

        button2 = (Button)findViewById(R.id.button2);
        button2.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                mColor = Color.parseColor("#fff000");
                background.setBackgroundColor(mColor);
            }
        });
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        // TODO Auto-generated method stub
        super.onSaveInstanceState(outState);
        outState.putInt(COLOR_VALUE, mColor);
    }
}
Alexander O'Mara
  • 58,688
  • 18
  • 163
  • 171
EricH
  • 21
  • 2

1 Answers1

3

You restored value but forgot about updating view, so:

if (savedInstanceState != null){
    mColor = savedInstanceState.getInt(COLOR_VALUE);
    background.setBackgroundColor(mColor);
}
asylume
  • 534
  • 3
  • 6