要實現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的時間。