Android custom countdown view

1 Inherit View

Whether we inherit the system View or directly inherit the View, we need to rewrite the constructor. There are multiple constructors, and at least one of them must be rewritten. For example, we create a new CountDownTextView to inherit AppCompatTextView

public class CountDownTextView extends AppCompatTextView

2 custom attributes

Android system controls start with android are the attributes of the system. In order to facilitate the configuration of custom View properties, we can also customize the property values.
Android custom attributes can be divided into the following steps:

  1. Customize a View
  2. Write values/attrs.xml, in which label elements such as styleable and item are written
  3. View uses custom attributes in the layout file (note the namespace)
  4. Obtained by TypedArray in View's construction method
<?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 define the countdown

 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秒后,返回首页");
    }

 

Guess you like

Origin blog.csdn.net/guodashen007/article/details/105101380