1

比如说,如果我希望 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 刚刚被破坏,但不是重新创建的

4

3 回答 3

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");
}

当您拥有大量数据时,例如来自数据库或数组列表的数据。

@Override 
public Object onRetainNonConfigurationInstance() {
final MyDataObject data = collectMyLoadedData(); 
return data;
}

在 onCreate

 final MyDataObject data = (MyDataObject) getLastNonConfigurationInstance();
if (data == null) {
    data = loadMyData();
}
于 2013-03-24T08:06:37.723 回答
0

我已经实现了一个可暂停的 CountDownTimer 并在调用 onPause()/onResume() 时暂停/恢复它,并在带有 setRetainInstance(true) 的片段中引用它。它现在可以在屏幕旋转或任何配置更改后保持进度。

于 2013-03-26T20:19:17.430 回答
0

您可以将计数是否完成存储在文件中

http://developer.android.com/guide/topics/data/data-storage.html

并在之后参考这个文件

于 2013-03-24T08:04:50.493 回答