在Android中使用Fragment显示当前时间

时间:2013-08-12 09:29:05

标签: android multithreading android-activity fragment

我目前正致力于在我的Android应用程序上显示当前时间。我已经得到了当前的时间,但我需要它是动态的;它应该每秒更新一次。我找到了这个解决方案,但是出了点问题:

public void onActivityCreated(Bundle savedInstanceState) {

    super.onActivityCreated(savedInstanceState);

    Thread timerThread = null;

    Runnable runnable = new CountDownRunner();
    timerThread = new Thread(runnable);
    timerThread.start();
}

public void doWork() {
    runOnUiThread(new Runnable() {
        public void run() {
            try {
                Date dt = new Date();
                int day = dt.getDate();
                int month = dt.getMonth();
                int hours = dt.getHours();
                int minutes = dt.getMinutes();
                int seconds = dt.getSeconds();
                String curTime = hours + ":" + minutes + ":" + seconds;
                time.setText(curTime);
            } catch (Exception e) {
            }
        }
    });
}

class CountDownRunner implements Runnable {
    // @Override
    public void run() {
        while (!Thread.currentThread().isInterrupted()) {
            try {
                doWork();
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
            } catch (Exception e) {
            }
        }
    }
}

错误在这一行:

runOnUiThread(new Runnable() {

我认为这个错误的原因是因为我在Fragment中实现它。它不会扩展到实现Thread所必需的Activity。

我尝试搜索并找到了一个可能的答案,其中我需要一个活动来扩展它 runOnUiThread ,但我还没有找到任何实现如何做到这一点。我现在感到困惑和困惑。

3 个答案:

答案 0 :(得分:2)

试试这个:getActivity().runOnUiThread(new Runnable...

这是因为:

1)您对 runOnUiThread 的调用中隐含的是指 AsyncTask,而不是片段

2)片段没有 runOnUiThread

答案 1 :(得分:1)

getActivity()。runOnUiThread(new Runnable(){

答案 2 :(得分:1)

如果您正在使用Fragment,请尝试使用:

getActivity().runOnUiThread(new Runnable(){
}

如果你在Activity中使用它,那么使用:

YourActivity.this.runOnUiThread(new Runnable() {
}
相关问题