在Android中使用片段显示当前时间

在Android中使用片段显示当前时间,android,multithreading,android-activity,fragment,Android,Multithreading,Android Activity,Fragment,我目前正在Android应用程序上显示当前时间。我已经得到了当前时间,但我需要它是动态的;它应该每秒钟更新一次。我找到了这个解决方案,但有点问题: public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); Thread timerThread = null; Runnable runnable = new CountD

我目前正在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) {
            }
        }
    }
}
错误在这一行:

rununuithread(新的Runnable(){

我认为这个错误的原因是因为我在片段中实现它。它没有扩展到实现线程所必需的活动


我试图搜索并找到一个可能的答案,其中我应该需要一个活动来扩展它到rununuithread,但我还没有找到任何实现方法。我现在不知何故感到困惑和结巴。

getActivity().rununuithread(new Runnable(){

getActivity().rununuithread(new Runnable()){

如果您使用的是Fragment,请尝试使用:

getActivity().runOnUiThread(new Runnable(){
}
如果您在活动中使用此选项,请使用:

YourActivity.this.runOnUiThread(new Runnable() {
}

如果您使用的是Fragment,请尝试使用:

getActivity().runOnUiThread(new Runnable(){
}
如果您在活动中使用此选项,请使用:

YourActivity.this.runOnUiThread(new Runnable() {
}

尝试以下操作:
getActivity().runOnUiThread(新的可运行…

这是因为:

1) 调用runOnUiThread时隐含的含义是指AsyncTask,而不是片段


2) Fragment没有runOnUiThread尝试以下操作:
getActivity().runOnUiThread(新的可运行…

这是因为:

1) 调用runOnUiThread时隐含的含义是指AsyncTask,而不是片段


(二)Fragment没有runOnUiThread

这可能会帮助您更好地实现它。这是官方Android TextClock:Wow的源代码。这是非常棒的信息。我会检查一下。谢谢@Milanix。这可能会帮助您更好地实现它。这是官方Android TextClock:Wow的源代码。非常棒信息。我会查一下。谢谢@Milanix。