屏幕旋转后,背景颜色会发生变化

时间:2014-08-17 01:11:02

标签: android

我创建了一个简单的Android应用程序,允许用户单击按钮并更改背景颜色。但是,在旋转设备后,颜色会变回默认值。我试图在onSavedInstanceState()方法中保存我的颜色,但无济于事。请参阅下面的代码

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);
    }
}

1 个答案:

答案 0 :(得分:3)

您恢复了价值,但忘了更新视图,所以:

if (savedInstanceState != null){
    mColor = savedInstanceState.getInt(COLOR_VALUE);
    background.setBackgroundColor(mColor);
}