【问题标题】:Display Current Time using Fragment in Android在 Android 中使用 Fragment 显示当前时间
【发布时间】:2013-08-12 09:29:05
【问题描述】:

我目前正致力于在我的 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 上扩展它,但我还没有找到任何实现方法。我现在不知何故感到困惑和卡住。

【问题讨论】:

标签: android multithreading android-activity fragment


【解决方案1】:

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

因为:

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

2) Fragment 没有 runOnUiThread

【讨论】:

    【解决方案2】:

    getActivity().runOnUiThread(new Runnable() {

    【讨论】:

      【解决方案3】:

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

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

      如果您在 Activity 中使用它,请使用:

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-01-17
        • 2021-08-01
        • 1970-01-01
        相关资源
        最近更新 更多