我在 onCreate() 方法中设置了一个条件来检查是否存在一些以前的数据。但它不起作用。请指导我。而且我不想对 this.d 使用 onRestoreSavedState() 方法
public class ActivityOne extends Activity {
当您在重新配置之间保存状态时,将它们用作键
private static final String RESTART_KEY = "restart";
private static final String RESUME_KEY = "resume";
private static final String START_KEY = "start";
private static final String CREATE_KEY = "create";
LogCat 文档的字符串
private final static String TAG = "Lab-ActivityOne";
private int mCreate=0, mRestart=0, mStart=0, mResume=0;
当它们相应的生命周期方法被调用时,您将需要增加这些变量的值。
TODO:为每个 TextView 创建变量
private TextView mTvCreate, mTvRestart, mTvStart, mTvResume;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_one);
TODO:将适当的 TextView 分配给 TextView 变量
mTvCreate=(TextView)findViewById(R.id.create);
mTvRestart=(TextView)findViewById(R.id.restart);
mTvResume=(TextView)findViewById(R.id.resume);
mTvStart=(TextView)findViewById(R.id.start);
Button launchActivityTwoButton = (Button) findViewById(R.id.bLaunchActivityTwo);
launchActivityTwoButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Intent intent=null;
intent = new Intent(v.getContext(),ActivityTwo.class);
startActivity(intent);
}
});
if(savedInstanceState!=null){
mCreate=savedInstanceState.getInt(String.valueOf(mCreate));
mRestart=savedInstanceState.getInt(String.valueOf(mRestart));
mResume=savedInstanceState.getInt(String.valueOf(mResume));
mStart=savedInstanceState.getInt(String.valueOf(mStart));
}
// Emit LogCat message
Log.i(TAG, "Entered the onCreate() method");
mCreate++;
displayCounts();
}
@Override
public void onSaveInstanceState(Bundle savedInstanceState) {
用一组键值对保存状态信息 4 行代码,每个计数变量一个 super.onSaveInstanceState(savedInstanceState);
savedInstanceState.putInt(String.valueOf(mCreate),mCreate);
savedInstanceState.putInt(String.valueOf(mRestart),mRestart);
savedInstanceState.putInt(String.valueOf(mResume),mResume);
savedInstanceState.putInt(String.valueOf(mStart),mStart);
}
更新显示的计数器 此方法要求计数器和 TextView 变量使用上面指定的名称 public void displayCounts() {
mTvCreate.setText("onCreate() calls: " + mCreate);
mTvStart.setText("onStart() calls: " + mStart);
mTvResume.setText("onResume() calls: " + mResume);
mTvRestart.setText("onRestart() calls: " + mRestart);
}
}