【问题标题】:Android: Periodically change the Text of a TextView of a Custom ListViewAndroid:定期更改自定义ListView的TextView的Text
【发布时间】:2019-03-22 02:26:53
【问题描述】:

在自定义 ListView 中,我有一个 TextView,其文本必须每 1 分钟定期更改为当前时间和日期。

所以我这样做了:

Timer mTimer = new Timer();
mTimer.scheduleAtFixedRate(new TimerTask() {
@Override
public void run() {

currentTime = System.currentTimeMillis();
(holder.myText).setText(new Date(currentTime));
}
}, 0, 60000);

在自定义适配器的getView中。

第一次有效,因为第一次设置Adapter时调用getView。

下次它给出异常:

android.view.ViewRoot$CalledFromWrongThreadException:只有创建视图层次结构的原始线程才能接触其视图。

那么我应该在哪里使用这个代码呢?

如果我的做法本身不好,请告诉我如何实现这一点。

谢谢

【问题讨论】:

  • 如果要在线程中更新 UI,请使用 runOnUiThread
  • 我认为即使是处理程序也可以正常工作
  • @Sharath This: java2s.com/Code/Android/UI/TimingActivity.htm 在 getView()??
  • 是的,在 getview() 中编写处理程序逻辑

标签: android listview timertask


【解决方案1】:

您不能从不是 UI 线程的线程更新 UI 对象。 试试这个:

this.runOnUiThread(new Runnable(){
   @Override
   public void run(){
       //update your TextView here
   }   
})

【讨论】:

  • 但是如何使这个 runOnUiThread 成为计划的。我的意思是我怎样才能每 1 分钟运行一次?
  • 看看 Android 处理程序。特别是在 postDelayed 方法;)
  • 看看java.util.Timer
【解决方案2】:

您也可以尝试以下链接中的示例。

http://www.java2s.com/Code/Android/UI/TimingActivity.htm

【讨论】:

  • 请不要发布链接。相反,显示几行代码来解释它的作用(在这种情况下,Handler.postDelayed(...)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-02-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-11-08
  • 1970-01-01
相关资源
最近更新 更多