我试图做一个计数器,并试图在离开应用程序时保存当前值,所以我尝试使用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
,所以我想知道语法是否正确,是否以正确的方式使用它?如果是这样,我的代码有什么问题?帮助和提示表示赞赏 最佳答案
您需要在方法中交换顺序,因为父级的实现方法将从方法中返回,并且您的代码将无法运行。另外,您需要检查onRestoreInstanceState
中的参数是否不为null。
public void onSaveInstanceState(Bundle savedInstanceState) {
savedInstanceState.putInt("counter", counter);
super.onSaveInstanceState(savedInstanceState);
}
@Override
public void onRestoreInstanceState(Bundle savedInstanceState) {
if (savedInstanceState != null) {
counter = savedInstanceState.getInt("counter");
}
super.onRestoreInstanceState(savedInstanceState);
}
你也说过
我试图做一个计数器,并试图在离开应用程序时保存当前值
保存实例状态仅在应用程序在内存中时有效(尽管离开应用程序不会将其删除)。如果被杀死,状态将丢失。