我刚看过这个: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? 并且工作但也许有比三嵌套if条件程序更好的东西?我的意思是我必须为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.
}
}
}
}
}
答案 0 :(得分:1)
也为您的活动设置一个变量,然后将其保存并使用您的状态恢复。
public class MyActivity extends Activity {
public static final String KEY_BUTTON_IS_GREEN = "isGreen";
boolean buttonIsGreen;
@Override
protected void onSaveInstanceState(Bundle outState) {
outState.putBoolean(KEY_BUTTON_IS_GREEN, buttonIsGreen);
super.onSaveInstanceState(outState);
}
@Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
buttonIsGreen = savedInstanceState.getBoolean(KEY_BUTTON_IS_GREEN, false);
if (buttonIsGreen){
// find the button and set it green.
}
}
您需要添加将按钮设置为绿色的方法,如果按钮为绿色,还需要设置变量= true。
答案 1 :(得分:1)
您有几个选择:
<activity name= ".YourActivity" android:configChanges="orientation|screenSize"/>
默认情况下不起作用,因为当您更改方向时,将再次调用onCreate并重新绘制视图。但是如果设置这些标志并且您正在为横向模式使用不同的布局,则通过添加这些参数,将不会调用横向模式的布局,因为onCreate将不会再次调用。
您可以通过以下方式保存int资源:
int colorFirst = answerOne.getHighlightColor();
savedInstanceState.putInt("key", colorFirst);