我正在尝试创建一个计数器并在您离开应用程序时尝试保存当前值,所以我尝试使用 onSaveInstanceState
但onRestoreInstanceState
它似乎不起作用
代码如下
package com.example.taekwondobuddy.util;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class Counter extends Activity {
int counter;
Button add;
Button sub;
TextView display;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.counter);
counter = 0;
add = (Button) findViewById(R.id.button1);
sub = (Button) findViewById(R.id.button2);
display = (TextView) findViewById(R.id.tvDisplay);
add.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
counter++;
display.setText("Counter: " + counter);
}
});
sub.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
counter--;
display.setText("Counter: " + counter);
}
});
}
public void onSaveInstanceState(Bundle savedInstanceState) {
super.onSaveInstanceState(savedInstanceState);
savedInstanceState.putInt("counter", counter);
}
@Override
public void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
counter = savedInstanceState.getInt("counter");
}
}
这是我第一次过度使用savedInstanceState
,所以我想知道语法是否正确,我是否以正确的方式使用它?如果是这样,我的代码有什么问题?帮助和提示表示赞赏