带时钟计时器的android对话框

时间:2014-02-06 22:49:05

标签: android timer android-handler

我想制作一个显示计时器的对话框。每一秒计时器值将增加。用户可以随时点击“确定”并关闭对话框。

对话框本身不是问题。但是如何创建将每秒执行给定过程的计时器?而且在用户关闭对话框后它将“不爆炸(=不会导致问题)”(然后对话框对象将不存在,因此处理程序过程应该能够检测到这种情况,而不是显示新的计时器值,它应该停止计时器。

提前感谢您的帮助。

1 个答案:

答案 0 :(得分:1)

我编写了一个示例代码,但我不确定它是否符合您的要求:

public class TimerDialog extends DialogFragment {

    private static final String TIME = "sec";

    private TextView mTime;
    private TimerTask mTimerTask;
    private long mSec;

    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {
        AlertDialog.Builder alert = new AlertDialog.Builder(getActivity());
        alert.setTitle("Timer");
        alert.setPositiveButton("OK", null);

        View view = View.inflate(getActivity(), R.layout.timer_dialog, null);
        mTime = (TextView) view.findViewById(R.id.time);

        alert.setView(view);
        return alert.create();
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        if (savedInstanceState != null) {
            mSec = savedInstanceState.getLong(TIME);
            mTime.setText(String.valueOf(mSec));
        }
        startTimer();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        stopTimer();
    }

    @Override
    public void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        outState.putLong(TIME, mSec);
    }

    private void startTimer() {
        Timer t = new Timer();

        mTimerTask = new TimerTask() {
            @Override
            public void run() {
                mSec++;
                getActivity().runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        mTime.setText(String.valueOf(mSec));
                    }
                });
            }
        };

        t.scheduleAtFixedRate(mTimerTask, 1000, 1000);
    }

    private void stopTimer() {
        mTimerTask.cancel();
    }
}

和timer_dialog:

<TextView xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/time"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:textAppearance="?android:attr/textAppearanceLarge"
    android:text="0"
    android:gravity="center" />