littlebot
Published on 2025-04-10 / 1 Visits
0

【源码】基于Android的倒计时按钮控件

项目简介

本项目提供了一个自定义的Android倒计时按钮控件(CountDownButton),适用于需要在Android应用中实现倒计时功能的场景,如获取验证码等。该控件支持多种自定义选项,包括按钮文字、颜色、倒计时时间等,并且兼容横竖屏切换,确保倒计时不间断。

项目的主要特性和功能

  1. 倒计时功能:提供基础的倒计时功能,支持自定义倒计时时间。
  2. 回调方法:可设置倒计时开始和结束的回调方法,方便执行特定操作。
  3. 自定义属性:支持在XML布局文件或Activity中设置按钮文字、文字颜色、倒计时时间等属性。
  4. 横竖屏兼容:横竖屏切换时,倒计时不间断。
  5. 记忆功能:倒计时开始后,应用返回或异常结束,再次进入应用时倒计时会继续。
  6. 持久化存储:使用SharedPreferences存储倒计时的状态和剩余时间,确保数据不丢失。
  7. 监听器支持:提供OnCountDownListener接口,允许用户注册监听器,在倒计时开始和结束时执行特定操作。

安装使用步骤

1. 添加自定义属性

values/attrs.xml文件中添加以下自定义属性: xml <declare-styleable name="CountDownButton"> <attr name="time" format="integer"/> <attr name="startText" format="string"/> <attr name="countDownText" format="string"/> <attr name="endText" format="string"/> <attr name="startTextColor" format="color"/> <attr name="countDownTextColor" format="color"/> <attr name="endTextColor" format="color"/> </declare-styleable>

2. 在XML中引用

在布局文件中添加命名空间,并引用CountDownButton控件: ```xml

<com.yxf.countdownbutton.CountDownButton
    android:id="@+id/count_down_button"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    app:time="10"/>

```

3. Activity调用方式

在Activity中初始化并使用CountDownButton控件: ```java public class MainActivity extends AppCompatActivity implements CountDownButton.OnCountDownListener {

private CountDownButton countDownButton;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    countDownButton = findViewById(R.id.count_down_button);
    countDownButton.setOnCountDownListener(this);
}

@Override
protected void onDestroy() {
    countDownButton.onDestroy();
    super.onDestroy();
}

@Override
public void OnStartCountDownListener(View countDownButton) {
    Toast.makeText(MainActivity.this, "开始倒计时", Toast.LENGTH_SHORT).show();
}

@Override
public void OnEndCountDownListener(View countDownButton) {
    Toast.makeText(MainActivity.this, "倒计时结束", Toast.LENGTH_SHORT).show();
}

} ```

4. 注意事项

  • 在Activity的onDestroy()方法中必须调用countDownButton.onDestroy(),以确保在Activity关闭后不会继续消耗资源。
  • OnStartCountDownListenerOnEndCountDownListener分别是开始倒计时和结束倒计时(正常结束、在异常结束和返回均不会触发)的回调函数。

下载地址

点击下载 【提取码: 4003】【解压密码: www.makuang.net】