MainActivity代码:
package com.example.time;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
private TextView tvCountdown;
private CountDownTimer countDownTimer;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tvCountdown = findViewById(R.id.tv_countdown);
startCountdown();
}
private void startCountdown() {
countDownTimer = new CountDownTimer(60000, 1000) {
@Override
public void onTick(long millisUntilFinished) {
tvCountdown.setText(String.valueOf(millisUntilFinished / 1000));
}
@Override
public void onFinish() {
tvCountdown.setText("0");
}
};
countDownTimer.start();
}
@Override
protected void onDestroy() {
super.onDestroy();
if (countDownTimer != null) {
countDownTimer.cancel();
}
}
}
activity_main.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<TextView
android:id="@+id/tv_countdown"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:textSize="24sp" />
</RelativeLayout>
标签:tvCountdown,void,private,倒计时,Studio,Override,import,Android,countDownTimer
From: https://blog.csdn.net/m0_75236614/article/details/139897042