你可以使用CountdownTimer類來創建一個簡單的計時器,下面是一個示例代碼:
import android.os.CountDownTimer;
import android.widget.TextView;
public class MyCountdownTimer extends CountDownTimer {
private TextView textView;
public MyCountdownTimer(long millisInFuture, long countDownInterval, TextView textView) {
super(millisInFuture, countDownInterval);
this.textView = textView;
}
@Override
public void onTick(long millisUntilFinished) {
long secondsUntilFinished = millisUntilFinished / 1000;
textView.setText("倒計時:" + secondsUntilFinished + "秒");
}
@Override
public void onFinish() {
textView.setText("倒計時結束");
}
}
然后在你的Activity中使用這個計時器:
public class MainActivity extends AppCompatActivity {
TextView textView;
MyCountdownTimer countdownTimer;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView = findViewById(R.id.textView);
countdownTimer = new MyCountdownTimer(60000, 1000, textView); // 倒計時60秒,每秒更新一次
countdownTimer.start();
}
}
這樣,你就可以在TextView中看到一個簡單的計時器,顯示倒計時的秒數,直到計時結束。