Java 反复运行代码

Java 反复运行代码,java,android,Java,Android,在我的应用程序中,我在文本视图中显示了一个时钟,我想实时更新它。我试着这样运行它: public void clock() { while(clock_on == true) { executeClock(); } } public void executeClock() { TextView timeTv = (TextView) findViewById(R.id.time); long currentTime=System.currentT

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

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);
}
但它不起作用。

请尝试:

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);
}
};
使用处理程序:

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);
    }
};

“不起作用”永远不是一个足够的问题描述。什么不起作用?您是否遇到任何错误?您是否尝试过循环时钟()调用而不是executeClock()?是否使用计时器并每隔一秒或更频繁地更新您的UI?灵感:
while
循环太快,UI无法更新。使用
处理程序
。这不是太频繁了吗?你必须做一个if语句而不是while。现在它看起来很正确:)但是我不确定在运行这个方法时是否缺少@Override。您不仅需要一个处理程序来从任何地方更新textview(处理程序在UI线程中运行),还可以使用它来运行延迟代码。。。因此,不要永远陷入一个while循环,只需每隔500-1000毫秒调用一次时钟更新。