效果图:
代码如下:
布局文件;
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:gravity="center"
android:padding="16dp">
<Button
android:id="@+id/btnGetCode"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="获取验证码"
android:textSize="18sp" />
</LinearLayout>
java代码;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.widget.Button;
import androidx.appcompat.app.AppCompatActivity;
public class MainActivity extends AppCompatActivity {
private Button btnGetCode;
private CountDownTimer countDownTimer;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnGetCode = findViewById(R.id.btnGetCode);
btnGetCode.setOnClickListener(view -> {
btnGetCode.setEnabled(false); // 禁用按钮
startCountDown(); // 开始倒计时
});
}
private void startCountDown() {
countDownTimer = new CountDownTimer(60000, 1000) { // 60秒倒计时,每秒更新一次
@Override
public void onTick(long millisUntilFinished) {
btnGetCode.setText("剩余 " + millisUntilFinished / 1000 + " 秒");
}
@Override
public void onFinish() {
btnGetCode.setText("获取验证码");
btnGetCode.setEnabled(true); // 启用按钮
}
}.start();
}
@Override
protected void onDestroy() {
super.onDestroy();
if (countDownTimer != null) {
countDownTimer.cancel(); // 防止内存泄漏
}
}
}