【问题标题】:Using timer for updating GUI: why it doesn't work?使用计时器更新 GUI:为什么它不起作用?
【发布时间】:2010-11-02 10:47:44
【问题描述】:

我正在创建一个用于视频录制的应用程序,并在视频预览上添加了标签 txtStatustxtTime

相机按钮启动/停止定时调用UpdateGUI方法的定时器。运行调试,我可以看到计时器正在工作 - 它每秒调用 updateGUI 方法,但该方法不会更新控件。

如果我能得到有关如何解决此问题的任何提示,我将不胜感激。

代码如下:

这是激活定时器的方法:

private void startTimer()
{
    updateTimer = new Timer("TimerUpdate");
    updateTimer.scheduleAtFixedRate(new TimerTask(){
        public void run(){
            settings.IncreaseRecordingTime();
            updateGUI();

        }
    }, 0, 1000);
}

这是 updateGUI 方法:

private void updateGUI()
{
    setStatusLabel();
    String strTime = settings.GetTimerString(); //strTime changes every second (it works as expected)
    txtTimer.setText(strTime);//the text doesn't change!
}

这是按下按钮时调用的方法:

private boolean onCaptureButton()
{
    settings.CaptureAction();
    videoPreview.setFrameCallback(settings);
    updateGUI();//here the function updateGUI() works as expected - it changes the txtStatus text from "Preview" to "Recording"
    setTimer();
    return false;
}

我还添加了一些 cmets(不知道为什么 updateGUI()onCaptureButton() 方法中调用时有效,而在计时器方法中调用时无效)。

【问题讨论】:

    标签: android user-interface timer


    【解决方案1】:

    定时器在定时器线程上运行。您应该只从 UI 线程更新 GUI。有几种方法可以做到这一点。最简单的方法之一是AsyncTasks 或将事件发布到 UI 处理程序。一些函数在非GUI 线程上调用时可以工作,但没有很好的记录。我从未见过刷新功能。我一直使用 invalidate(UI 线程)或 postInvalidate(后台线程)。我认为 setText 在内部调用了它。

    【讨论】:

      【解决方案2】:

      在更新每个控件调用 control.Refresh()form.Refresh() - 这会强制立即重绘控件。

      在你的情况下:

      txtTimer.setText(strTime); // the text doesn't change!
      txtTimer.Refresh(); 
      

      【讨论】:

      • 我尝试使用 txtTimer.refreshDrawableState();但它不起作用。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-09-14
      • 2021-12-18
      • 1970-01-01
      • 2017-11-28
      • 1970-01-01
      • 1970-01-01
      • 2011-03-15
      相关资源
      最近更新 更多