通过Handler更新时间
时间: 2023-08-10 17:29:04 浏览: 86
可以使用Handler的postDelayed方法来实现定时更新时间。首先,在Activity或Fragment中创建一个Handler对象,并在onCreate方法中调用post方法来更新时间:
```
private Handler mHandler = new Handler();
private TextView mTimeTextView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mTimeTextView = findViewById(R.id.time_text_view);
// 调用post方法更新时间
mHandler.post(updateTimeTask);
}
```
然后,创建一个Runnable对象,在run方法中更新时间,并使用postDelayed方法来定时调用这个Runnable:
```
private Runnable updateTimeTask = new Runnable() {
public void run() {
// 更新时间
updateTime();
// 延迟1秒后再次调用run方法
mHandler.postDelayed(this, 1000);
}
};
private void updateTime() {
// 更新时间TextView
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String time = sdf.format(new Date());
mTimeTextView.setText(time);
}
```
这样就可以实现定时更新时间了。当Activity或Fragment被销毁时,需要调用removeCallbacks方法来停止定时任务:
```
@Override
protected void onDestroy() {
super.onDestroy();
// 停止定时任务
mHandler.removeCallbacks(updateTimeTask);
}
```
阅读全文
相关推荐
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![application/x-zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![docx](https://img-home.csdnimg.cn/images/20241231044901.png)
![doc](https://img-home.csdnimg.cn/images/20241231044833.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231044955.png)
![-](https://img-home.csdnimg.cn/images/20241231044833.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)