你可以使用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中看到一个简单的计时器,显示倒计时的秒数,直到计时结束。