要实现TextClock自动更新时间,可以使用Handler和Runnable来定时更新TextClock的时间。具体步骤如下:
示例代码如下:
public class MainActivity extends AppCompatActivity {
private Handler mHandler;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final TextClock textClock = findViewById(R.id.textClock);
mHandler = new Handler();
mHandler.post(new Runnable() {
@Override
public void run() {
textClock.setText(new SimpleDateFormat("HH:mm:ss").format(new Date()));
mHandler.postDelayed(this, 1000); // 每秒更新一次时间
}
});
}
@Override
protected void onResume() {
super.onResume();
mHandler.postDelayed(new Runnable() {
@Override
public void run() {
mHandler.postDelayed(this, 1000);
}
}, 1000);
}
@Override
protected void onPause() {
super.onPause();
mHandler.removeCallbacksAndMessages(null);
}
}
以上代码会在每秒更新TextClock的时间。