安卓自定义倒计时View

1继承View

无论是我们继承系统View还是直接继承View,都需要对构造函数进行重写,构造函数有多个,至少要重写其中一个才行。如我们新建CountDownTextView继承AppCompatTextView

public class CountDownTextView extends AppCompatTextView

2 自定义属性

Android系统的控件以android开头的都是系统自带的属性。为了方便配置自定义View的属性,我们也可以自定义属性值。
Android自定义属性可分为以下几步:

  1. 自定义一个View
  2. 编写values/attrs.xml,在其中编写styleable和item等标签元素
  3. 在布局文件中View使用自定义的属性(注意namespace)
  4. 在View的构造方法中通过TypedArray获取
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <declare-styleable name="test">
        <attr name="counttime" format="integer" />
    </declare-styleable>
</resources>

<com.layout.CountDownTextView
        app:counttime="180"
       ></com.layout.CountDownTextView>
public CountDownTextView(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        TypedArray ta = context.obtainStyledAttributes(attrs, R.styleable.test);
        long test_counttime = ta.getInteger(R.styleable.test_counttime, 120);
        TOTAL_TIME=test_counttime*1000;
        ta.recycle();
        Log.e(TAG, "test_counttime = " + TOTAL_TIME);
        
    }

3定义倒计时

 public void startCountTime() {
        countDownTimer = new CountDownTimer(TOTAL_TIME, ONCE_TIME) {
            @Override
            public void onTick(long millisUntilFinished) {
              
               String value = String.valueOf((int) (millisUntilFinished / 1000));
               setText("倒计时"+value +"秒后,返回首页");
            }

            @Override
            public void onFinish() {
             };
        
        countDownTimer.start();
    }


    public void stopCountTime() {
    if(countDownTimer!=null){
        countDownTimer.cancel();
        countDownTimer=null;
        setText("倒计时120秒后,返回首页");
    }

猜你喜欢

转载自blog.csdn.net/guodashen007/article/details/105101380
今日推荐