在Android中显示当前时间并进行更新?
问题描述:
我想显示当前时间并保持更新,例如: 09:41 Hour:Minute.是否可以在 TextView
中进行?我尝试了一些方法,但没有得到我真正想要的.
I want to display current time and keep it updating, in this format example: 09:41 Hour:Minute. Is it possible to do in TextView
? I tried some ways but I'm not getting what I actually want.
答
这种方法应该可以解决问题
Something like this should do the trick
final Handler someHandler = new Handler(getMainLooper());
someHandler.postDelayed(new Runnable() {
@Override
public void run() {
tvClock.setText(new SimpleDateFormat("HH:mm", Locale.US).format(new Date()));
someHandler.postDelayed(this, 1000);
}
}, 10);
当 Activity
暂停并恢复时,您应该保留对处理程序和可运行对象的引用,以取消此操作.确保删除所有对处理程序的回调并将其在 onDestroy
You should keep a reference to the handler and the runnable to cancel this when the Activity
goes to pause and resume when it resumes. Make sure you remove all callbacks to handler and set it to null
in onDestroy