我正在开发一个基础的Android应用,每当我点击按钮时,它会在TextView中加上一个数字。使用onSaveInstanceState()和onRestoreInstanceState()函数,TextView中显示的数字也会在手机旋转时保留下来。
问题在于,当手机旋转后,数值被保留下来,但是当再次按下按钮后,它又从0开始计数,而不是从保存的值开始计数。
我的代码:
public class MainActivity extends AppCompatActivity {
TextView showValue;
int counter=0;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
showValue = (TextView) findViewById(R.id.CounterValue);
}
public void countIN(View view)
{
counter++;
showValue.setText(Integer.toString(counter));
}
@Override
protected void onSaveInstanceState(Bundle outState) {
outState.putString("my_text", showValue.getText().toString());
super.onSaveInstanceState(outState);
}
@Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
showValue.setText(savedInstanceState.getString("my_text"));
}
}
感谢您的回复。