【问题标题】:Run code over and over一遍又一遍地运行代码
【发布时间】:2012-07-30 16:00:45
【问题描述】:

在我的应用程序中,我在TextView 中显示了一个时钟,我想实时更新它。我试着这样运行它:

public void clock() {
    while(clock_on == true) {
        executeClock();
    }
}

public void executeClock() {
    TextView timeTv = (TextView) findViewById(R.id.time);
    long currentTime=System.currentTimeMillis();
    Calendar cal=Calendar.getInstance();
    cal.setTimeInMillis(currentTime);
    String showTime=String.format("%1$tI:%1$tM %1$Tp",cal);
    timeTv.setText(showTime);
}

但它不起作用。

【问题讨论】:

  • “不起作用”从不足以说明问题。 stackoverflow.com/questions/how-to-ask
  • 什么不起作用?你有什么错误吗?
  • 你试过循环clock()调用而不是executeClock()吗?
  • 如何使用计时器并每秒更新一次用户界面,或者如果您愿意,可以更频繁地更新您的用户界面......?灵感:stackoverflow.com/a/6702767/1525300.
  • 您的while 循环太快,UI 无法更新。使用Handler

标签: java android


【解决方案1】:

请尝试:

private Handler handler = new Handler();
runnable.run();

private Runnable runnable = new Runnable() 
{

public void run() 
{
     //
     // Do the stuff
     //
     if(clock_on == true) {

             executeClock();

     }

     handler.postDelayed(this, 1000);
}
};

【讨论】:

  • 那会不会太频繁了?你必须做一个 if 语句而不是你的 while。
  • 现在看起来很正确 :) 但我不确定运行方法中是否缺少 @Override
【解决方案2】:

使用处理程序:

private Handler handler = new Handler() {

    @Override
    public void handleMessage(android.os.Message msg) {
            TextView timeTv = (TextView) findViewById(R.id.time);
            long currentTime=System.currentTimeMillis();
            Calendar cal=Calendar.getInstance();
            cal.setTimeInMillis(currentTime);
            String showTime=String.format("%1$tI:%1$tM %1$Tp",cal);
            timeTv.setText(showTime);

            handler.sendEmptyMessageDelayed(0, 1000);
    }
};

【讨论】:

  • 这个。您不仅需要一个处理程序来能够从任何地方更新文本视图(处理程序在 UI 线程中运行),您还可以使用它来运行延迟的代码......所以不要永远卡在 while 循环中,只需调用你的时钟每 500-1000 毫秒更新一次。
猜你喜欢
  • 2017-02-19
  • 1970-01-01
  • 2017-09-20
  • 2021-01-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多