比方说,如果我希望CountDownTimer在完成后更新一些UI元素,但在倒计时中间有一个配置更改,强制重新创建活动。
public class MyActivity extends Activity {
private TextView textView;
....
public void onButtonClicked(View view)
{
// start CountDownTimer
new CountDownTimer(10000, 10000) {
public void onTick(long millisUntilFinished) {
// do nothing
}
public void onFinish() {
textView.setText("Hello World!");
}
}.start();
}
}
我发现当CountDownTimer完成时,它会在刚被销毁的活动中设置textView,但不会重新创建一个
答案 0 :(得分:1)
http://developer.android.com/guide/topics/resources/runtime-changes.html
@Override
public void onSaveInstanceState(Bundle savedInstanceState) {
super.onSaveInstanceState(savedInstanceState);
// Save UI state changes to the savedInstanceState.
// This bundle will be passed to onCreate if the process is
// killed and restarted.
savedInstanceState.putString("timer",1223);
// etc.
}
@Override
public void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
// Restore UI state from the savedInstanceState.
// This bundle has also been passed to onCreate.
time = savedInstanceState.getString("time");
}
当您拥有大量数据时,例如来自数据库或arraylist的数据。
@Override
public Object onRetainNonConfigurationInstance() {
final MyDataObject data = collectMyLoadedData();
return data;
}
在onCreate
final MyDataObject data = (MyDataObject) getLastNonConfigurationInstance();
if (data == null) {
data = loadMyData();
}
答案 1 :(得分:0)
答案 2 :(得分:0)
我已经实现了一个可调用的CountDownTimer,并在调用onPause()/ onResume()时暂停/恢复它,并使用setRetainInstance(true)在片段中引用它。它现在可以在屏幕旋转或任何配置更改后保持其进度。