0

在我的应用程序中,我在 a 中显示了一个时钟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);
}

但它不起作用。

4

2 回答 2

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);
}
};
于 2012-07-30T16:03:54.837 回答
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);
    }
};
于 2012-07-30T16:05:06.923 回答