一遍又一遍地运行代码

时间:2012-07-30 16:00:45

标签: java android

在我的应用程序中,我在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);
}

但它不起作用。

2 个答案:

答案 0 :(得分:4)

请尝试:

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

答案 1 :(得分:3)

使用处理程序:

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);
    }
};
相关问题