如何在触摸屏关闭后禁用活动的新实现?
注意:设备未关闭,但触摸屏也已关闭。
例如,请参阅以下代码,当我们点击imageView
对象时,随时将1
单位增加到textView
对象值。如果我们在imageView
对象上单击十次,则textView
对象将具有10
值。现在如果我没有点击触摸屏,结果触摸屏将关闭。现在,当我想打开触摸屏时,textView
对象值为0
。虽然它应该具有相同的10
值。
public class MainActivity extends Activity {
ImageView imageView;
Integer integer = 0;
TextView textView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
imageView = (ImageView) findViewById(R.id.imageView);
textView = (TextView) findViewById(R.id.textView);
textView.setText(integer.toString());
imageView.setOnClickListener(new View.OnClickListener() {@Override
public void onClick(View v) {
integer = integer + 1;
textView.setText(integer.toString());
}
});
}
}
答案 0 :(得分:1)
您必须使用onSaveInstanceState来保存您的状态
public class MainActivity extends Activity {
ImageView imageView;
Integer integer = 0;
TextView textView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
imageView = (ImageView) findViewById(R.id.imageView);
textView = (TextView) findViewById(R.id.textView);
if (savedInstanceState!=null) {
integer = savedInstanceState.getInt("count");
}
textView.setText(integer.toString());
imageView.setOnClickListener(new View.OnClickListener() {@Override
public void onClick(View v) {
integer = integer + 1;
textView.setText(integer.toString());
}
});
}
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putInt("count", integer);
}
}
http://developer.android.com/training/basics/activity-lifecycle/recreating.html#SaveState