Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

自製滑動開關:從 CompoundButton 源碼到 SwitchButton 實作

編輯:關於 Android 程式設計

版本 1.0,2014.5.17 起筆、2014.6.1 補完。版權 © 2014 kince,轉載請註明出處。

要自己寫一個滑動開關,先回頭看系統是怎麼做的會省很多力氣。

一、Button 其實很單純

@RemoteView
public class Button extends TextView {
    public Button(Context context) { this(context, null); }
    public Button(Context context, AttributeSet attrs) {
        this(context, attrs, com.android.internal.R.attr.buttonStyle);
    }
    public Button(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
    }
    ...
}

Button 直接繼承 TextView,差別只在建構子中帶入了 buttonStyle 樣式,並自行處理無障礙相關的初始化。但並非所有子類都這麼輕薄。

Button 的直接子類只有一個抽象類 CompoundButton,而 CheckBox、RadioButton、Switch、ToggleButton 四者都實作自它。因此 CompoundButton 才是重點。

二、CompoundButton 的關鍵設計

建構子中讀取兩個屬性:一個 Drawable 用於設置「按鈕圖」,一個 boolean 表示是否已勾選。

public CompoundButton(Context context, AttributeSet attrs, int defStyle) {
    super(context, attrs, defStyle);
    TypedArray a = context.obtainStyledAttributes(attrs,
            com.android.internal.R.styleable.CompoundButton, defStyle, 0);
    Drawable d = a.getDrawable(com.android.internal.R.styleable.CompoundButton_button);
    if (d != null) { setButtonDrawable(d); }
    boolean checked = a.getBoolean(com.android.internal.R.styleable.CompoundButton_checked, false);
    setChecked(checked);
    a.recycle();
}

setButtonDrawable 寫得很值得學習。它先判斷傳入的 Drawable 是否為空,若不為空且原本已有 Drawable,就先取消舊 Drawable 的 callback 並呼叫 unscheduleDrawable 把它從 Choreographer 的動畫佇列中摘除,再設定新的 callback、可見性與最小高度,最後呼叫 refreshDrawableState() 更新狀態。換 Drawable 時主動清理舊物件,是避免記憶體與 callbacks 殘留的標準做法。

setChecked 裡藏著一個巧妙手法:

public void setChecked(boolean checked) {
    if (mChecked != checked) {
        mChecked = checked;
        refreshDrawableState();
        notifyViewAccessibilityStateChangedIfNeeded(...);
        // 避免 listener 中再呼叫 setChecked 造成無限遞迴
        if (mBroadcasting) { return; }
        mBroadcasting = true;
        if (mOnCheckedChangeListener != null) {
            mOnCheckedChangeListener.onCheckedChanged(this, mChecked);
        }
        if (mOnCheckedChangeWidgetListener != null) {
            mOnCheckedChangeWidgetListener.onCheckedChanged(this, mChecked);
        }
        mBroadcasting = false;
    }
}

一個 mBroadcasting 旗標就擋掉了「在 listener 回呼裡改狀態」導致的無限遞迴,這個模式在 Android 原始碼中到處可見,值得直接借用。

onDraw 的重點是算出四邊座標:依垂直方向的 gravity 決定 top(靠下、居中或預設),bottom 由 top 加上圖片高度得出,left/right 則視 isLayoutRtl() 判斷是否要鏡像,最後 setBounds 後畫上去。

三、子類有多簡單

CheckBox 幾乎就是 Button 的翻版,只是換用自己的 checkboxStyle。RadioButton additionally 覆寫了 toggle(),避免已勾選時又被切回:

@Override
public void toggle() {
    // 已勾選的 radio button 不允許再切換(與 checkbox 不同)
    if (!isChecked()) {
        super.toggle();
    }
}

ToggleButton 的實作同樣單純,Switch 稍複雜一些,有興趣可自行追。這也說明一件事:換湯不換藥的差異都靠覆寫少數幾個方法解決,共用邏輯全在 CompoundButton。

四、滑動開關的實作思路

圖 1-1

圖 1-2

原理很單純:一張背景圖畫著「開/關」兩段文字,上面蓋一顆圓鈕;圓鈕左右滑動時遮住其中一側,於是任一時刻只看得見一個狀態。

實作上就是先畫背景,再在其上計算並畫出圓鈕位置,滑動時只需要更新圓鈕的 X 座標。

準備素材

滑塊圖:

背景圖(開/關兩款):

為什麼直接繼承 View

自訂控制項可以繼承 Button、繼承 Button 的子類,也可以直接繼承 View。滑動開關就是「左右滑動改變顯示內容」這麼一件事,不需要 Button 的剩餘能力;若繼承系統控制項,反而會帶進一堆用不到的機制。因此直接繼承 View 最合適。

實作步驟:

  1. 定義類別繼承 View,在建構子中載入圖片並取得各自寬高。
  2. 覆寫 onMeasure() 決定控制項尺寸。
  3. 覆寫 onTouchEvent() 判別滑動手勢。
  4. 定義 callback 介面。
  5. 覆寫 onDraw() 動態繪製按鈕。

五、核心程式碼

public class SlideButton extends View {

    private Bitmap slideBitMap;   // 滑塊圖
    private Bitmap switchBitMap;  // 背景圖
    private int slideBitMapWidth;
    private int switchBitMapWidth;
    private int switchBitMapHeight;

    private boolean currentState;   // 開關狀態
    private boolean isSliding = false;  // 是否正在滑動中
    private int currentX;           // 目前滑塊位置

    private OnToggleStateChangedListener mChangedListener;  // 回呼介面

    public SlideButton(Context context) { this(context, null); }
    public SlideButton(Context context, AttributeSet attrs) { this(context, attrs, 0); }

    public SlideButton(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        initBitmap();
    }

    private void initBitmap() {
        slideBitMap  = BitmapFactory.decodeResource(getResources(), R.drawable.slide_button_background);
        switchBitMap = BitmapFactory.decodeResource(getResources(), R.drawable.switch_background);
        slideBitMapWidth  = slideBitMap.getWidth();
        switchBitMapWidth = switchBitMap.getWidth();
        switchBitMapHeight = switchBitMap.getHeight();
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        // 控制項尺寸直接取背景圖尺寸
        setMeasuredDimension(switchBitMapWidth, switchBitMapHeight);
    }

    @Override
    protected void onDraw(Canvas canvas) {
        canvas.drawBitmap(switchBitMap, 0, 0, null);

        if (isSliding) {
            // 滑動中:依目前 X 座標即時計算,並夾在合法範圍內
            int dis = currentX - slideBitMapWidth / 2;
            if (dis < 0) dis = 0;
            else if (dis > switchBitMapWidth - slideBitMapWidth) {
                dis = switchBitMapWidth - slideBitMapWidth;
            }
            canvas.drawBitmap(slideBitMap, dis, 0, null);
        } else {
            // 靜止:依狀態畫在最左或最右
            if (currentState) {
                canvas.drawBitmap(slideBitMap, switchBitMapWidth - slideBitMapWidth, 0, null);
            } else {
                canvas.drawBitmap(slideBitMap, 0, 0, null);
            }
        }
        super.onDraw(canvas);
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN:
                isSliding = true;
                currentX = (int) event.getX();
                break;
            case MotionEvent.ACTION_MOVE:
                currentX = (int) event.getX();
                break;
            case MotionEvent.ACTION_UP:
                isSliding = false;
                // 以背景中線判斷最終狀態
                boolean state = currentX > switchBitMapWidth / 2;
                if (state != currentState && mChangedListener != null) {
                    mChangedListener.onToggleStateChanged(state);
                }
                currentState = state;
                break;
        }
        invalidate();
        return true;
    }

    public boolean isToggleState() { return currentState; }
    public void setToggleState(boolean currentState) { this.currentState = currentState; }
    public void setmChangedListener(OnToggleStateChangedListener l) { this.mChangedListener = l; }
}

回呼介面:

public interface OnToggleStateChangedListener {
    void onToggleStateChanged(boolean state);
}

使用端在 Fragment 中註冊監聽並做 Toast 提示:

slidebutton = (SlideButton) rootView.findViewById(R.id.slidebutton1);
slidebutton.setToggleState(true);          // 設定初始為開
slidebutton.setmChangedListener(this);

@Override
public void onToggleStateChanged(boolean state) {
    FragmentActivity activity = getActivity();
    Toast.makeText(activity, state ? "開關打開" : "開關關閉", 0).show();
}

六、幾點設計說明

  • onMeasure 直接回傳背景圖尺寸是因為素材本身已決定外觀大小,不需要再支援 wrap_content 的內容測量。
  • onDraw 中的 clamp確保滑塊不會滑出背景範圍,滑到邊界就停住。
  • 狀態只在 ACTION_UP 提交,滑動過程中不觸發 listener,避免使用者手指移過中線又移回時產生誤觸。
  • onTouchEvent 回傳 true表示事件已被消費,避免父容器搶走手勢。

後續可優化的方向還不少:改用自訂屬性在 XML 中指定素材、加入滑動動畫曲線、支援點擊直接切換、以及處理控制項禁用狀態。未完待續。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved