gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 16:06:09 24 4
gpt4 key购买 nike

我目前正在努力在我的 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 中实现它。它不会扩展到实现线程所必需的 Activity 。

我尝试搜索并找到了一个可能的答案,其中我需要一个 Activity 来在 <​​strong>runOnUiThread 上扩展它,但我还没有找到任何实现方法。我现在不知何故感到困惑和困惑。

最佳答案

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

这是因为:

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

2) Fragment 没有runOnUiThread

关于android - 在 Android 中使用 Fragment 显示当前时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18183622/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com