嗨,有人可以解释我,我做错了,因为我无法从savedInstanceState获取变量,每次更改屏幕方向时int“得分”都会重置变量。
int score;
EditText et;
String etString;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
et = (EditText) findViewById(R.id.editText);
if (savedInstanceState != null) {
score = savedInstanceState.getInt("score");
et.setText(savedInstanceState.getString("etText"));
Log.d("TEST2", "score " + score);
} else {
score = 0;
}
}
@Override
public void onSaveInstanceState(Bundle outState, PersistableBundle outPersistentState) {
super.onSaveInstanceState(outState, outPersistentState);
etString = et.getText().toString();
outState.putString("etText", etString);
outState.putInt("score", score);
Log.d("TEST", "score " + score);
}
public void performAction(View v) {
switch (v.getId()) {
case R.id.button:
score += 1;
break;
case R.id.button2:
Toast.makeText(getApplicationContext(), "Score: " + score, Toast.LENGTH_LONG).show();
break;
}
}
如果您知道解决方案,请提供帮助。
答案 0 :(得分:1)
您正在使用来自Lollipop的方法,更改为自Android 1.0以来可用的版本
@Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
看到不同的方法签名?
答案 1 :(得分:0)
您应该实施onRestoreInstanceState
而不是onCreate
中的价值。仅当存在要恢复的已保存状态时,系统才会调用onRestoreInstanceState(),因此您无需检查Bundle是否为空。
答案 2 :(得分:0)
public class OrientationChangeActivity extends Activity {
private EditText edtUser;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
edtUser = (EditText) findViewById(R.id.edtUsername);
if (savedInstanceState != null /*&& savedInstanceState.getString("edt") != null*/) {
edtUser.setText(savedInstanceState.getString("edt"));
Log.e("Demo","==================================="+savedInstanceState.getString("edt"));
}
}
@Override
protected void onSaveInstanceState(Bundle outState) {
outState.putString("edt", edtUser.getText().toString());
super.onSaveInstanceState(outState);
}
}