4.實戰之倒計時案例(鞏固Handler的使用)

1、實現效果

如下圖所示:
這裏寫圖片描述

2、代碼實現

新建一個名爲CountdownTime的項目,activity_main.xml代碼如下:

<?xml version="1.0" encoding="utf-8"?>
<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/countdownTimeTextView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:text="@string/maxTime"
        android:textSize="60sp" />
</RelativeLayout>

MainActivity.class代碼如下:

public class MainActivity extends AppCompatActivity {

    /**
     * 倒計時標記
     */
    public static final int COUNTDOWN_TIME_CODE = 99999;
    /**
     * 倒計時間隔
     */
    public static final int DELAY_MILLIS = 1000;
    /**
     * 倒計時最大值
     */
    public static final int MAX_COUNT = 10;
    /**
     * 文本控件
     */
    private TextView countdownTimeTextView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        //初始化文本控件
        countdownTimeTextView = findViewById(R.id.countdownTimeTextView);
        //創建一個handler
        CountdownTimeHandler handler = new CountdownTimeHandler(this);
        //新建一個message
        Message message = Message.obtain();
        message.what = COUNTDOWN_TIME_CODE;
        message.arg1 = MAX_COUNT;
        //第一次發送message
        handler.sendMessageDelayed(message, DELAY_MILLIS);
    }

    public static class CountdownTimeHandler extends Handler {
        /**
         * 倒計時最小值
         */
        public static final int MIN_COUNT = 0;
        //創建MainActivity弱引用
        final WeakReference<MainActivity> mWeakReference;

        public CountdownTimeHandler(MainActivity activity) {
            this.mWeakReference = new WeakReference<>(activity);
        }

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            //獲取對MainActivity的弱引用
            MainActivity activity = mWeakReference.get();
            switch (msg.what) {
                case COUNTDOWN_TIME_CODE:
                    int value = msg.arg1;
                    activity.countdownTimeTextView.setText(String.valueOf(value--));
                    //循環發送消息的控制
                    if (value >= MIN_COUNT) {
                        Message message = Message.obtain();
                        message.what = COUNTDOWN_TIME_CODE;
                        message.arg1 = value;
                        sendMessageDelayed(message, DELAY_MILLIS);
                    }
                    break;
            }
        }
    }
}

3、快捷鍵總結

Ctrl+Alt+F:改變變量的域
Ctrl+Alt+T:surrounded with快捷鍵
Ctrl+P:查看方法的參數

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章