【发布时间】:2017-12-04 23:05:38
【问题描述】:
我刚读到这个:Saving Android Activity state using Save Instance State
这个:Android - Open resource from @drawable String
我的情况是:我有一个按钮背景设置为按下时为绿色
button.setBackgroundResource(R.drawable.greenbutton);
如何使用 onSaveInstanceState 和 onRestoreInstanceState 存储这些信息?
我试过了:How to maintain a button style and click state after screen rotation? 并且工作了,但也许有比三嵌套如果条件程序更好的方法?我的意思是我必须为 4+ Button 做这个,我认为这只是一个简单的原因:)
谢谢
编辑:这是目前的代码
package com.example.android.testbutton;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button = (Button) findViewById(R.id.change);
}
Button button;
Boolean click;
public void changeColor(View view) {
click = true;
button.setBackgroundResource(R.drawable.greenbutton);
}
@Override
public void onSaveInstanceState(Bundle savedInstanceState) {
// Save UI state changes to the savedInstanceState.
// This bundle will be passed to onCreate if the process is
// killed and restarted.
savedInstanceState.putBoolean("buttonClicked", click);
// etc.
super.onSaveInstanceState(savedInstanceState);
}
//onRestoreInstanceState
@Override
public void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
// Restore UI state from the savedInstanceState.
// This bundle has also been passed to onCreate.
Boolean firstAnswer = savedInstanceState.getBoolean("buttonClicked");
{
if (savedInstanceState != null) {
if (savedInstanceState.containsKey("buttonClicked")) {
if (savedInstanceState.getBoolean("buttonClicked"))
button.setBackgroundResource(R.drawable.greenbutton);
//some codes to make the button becomes clicked.
}
}
}
}
}
【问题讨论】:
-
你在哪里设置默认颜色?放更多代码
-
添加了我正在处理的 Java 代码
标签: java android button screen-rotation