在我的应用程序中,我在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);
}
但它不起作用。
答案 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);
}
};