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

自定義狀態切換控件:SwitchButton 與 SegmentControl 的三種實現

編輯:關於 Android 程式設計

開關與頁面/狀態切換在 Android 中隨處可見,原生也有 RadioGroup、TabHost 等方案。本文換個角度,參照 iOS 兩種常見樣式——SwitchButton 與 SegmentControl——用自定義 View 做三種實現,順帶複習測量、繪製與狀態保存。

整體實現了按鈕切換與頁面切換兩種形態、三套方案:兩種 SwitchButton(組合 View、純繪製)與一種 SegmentControl。重點放在 SwitchButton 的繪製上,SegmentControl 的繪製思路同理可推。

效果圖:

頂部是切換頁面的 SegmentControl,第一行是組合 View 實現的 SwitchButton,第二行則是完全繪製出來的版本。

一、SwitchButton 實現(一):組合 View

狀態開關最常用於設定頁的選項切換。

布局

三個 View 疊放:開啟狀態背景、關閉狀態背景、中間的圓形按鈕。點擊時用動畫移動圓鈕並切換背景透明度,做出類似的視覺效果。

<merge xmlns:android="https://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <FrameLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content">

        <ImageView
            android:id="@+id/on_bg_view"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:src="@drawable/switch_on_bg" />

        <ImageView
            android:id="@+id/off_bg_view"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:src="@drawable/switch_off_bg" />
    </FrameLayout>

    <ImageView
        android:id="@+id/circle_view"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:src="@drawable/switch_circle" />
</merge>

頂層用 merge 是因為它會被 inflate 進 FrameLayout,多一層根節點只會徒增層級。

成員與構造

public class SwitchView extends FrameLayout {

    protected boolean isChecked;              // 是否選中
    protected View onBgView;
    protected View offBgView;
    protected View circleView;
    protected boolean autoForPerformClick = true;   // 是否點擊即自動切換
    protected OnCheckedChangedListener onCheckedChangedListener;

    public SwitchView(Context context) {
        super(context);
        initialize();
    }

    public SwitchView(Context context, AttributeSet attrs) {
        super(context, attrs);
        initialize();
    }

    public SwitchView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        initialize();
    }

    protected void initialize() {
        setClickable(true);
        LayoutInflater layoutInflater = (LayoutInflater)
                getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        layoutInflater.inflate(R.layout.switch_view, this);
        onBgView   = findViewById(R.id.on_bg_view);
        offBgView  = findViewById(R.id.off_bg_view);
        circleView = findViewById(R.id.circle_view);
    }
}

為什麼要重寫 performClick

一般的狀態切換由 click 監聽配合業務邏輯判斷是否切換。但 SwitchButton 的直觀感受是「先切換狀態,再執行後續動作」,因此把切換邏輯放進 performClick,讓點擊與狀態變化同步發生。

@Override
public boolean performClick() {
    if (!autoForPerformClick) {
        return super.performClick();   // 交給默認處理
    }
    setChecked(!isChecked, true);
    if (onCheckedChangedListener != null) {
        onCheckedChangedListener.onChanged(this, isChecked);
    }
    return super.performClick();
}

performClick() 是 View 中真正被呼叫、並據此決定是否觸發 OnClickListener 的方法,重寫它可以插入自己的邏輯。

切換動畫

打開時圓鈕從左滑到右、onBg 淡入;關閉時反向。

public void setChecked(boolean value, boolean needAnimate) {
    if (isChecked == value) return;
    isChecked = value;

    float targetX = 0;
    if (getWidth() != 0) {
        targetX = getWidth() - circleView.getWidth();
    } else {
        // view 尚未渲染上去時 getWidth() 為 0,改用測量值
        measure(0, 0);
        targetX = getMeasuredWidth() - circleView.getMeasuredWidth();
    }

    long durationMillis = needAnimate ? 200 : 0;

    if (isChecked) {
        onBgView.bringToFront();
        onBgView.setVisibility(View.VISIBLE);
        offBgView.setVisibility(View.VISIBLE);

        TranslateAnimation an1 = new TranslateAnimation(0, targetX, 0, 0);
        an1.setFillAfter(true);
        an1.setDuration(durationMillis);
        circleView.startAnimation(an1);

        AlphaAnimation an2 = new AlphaAnimation(0, 1);
        an2.setFillAfter(true);
        an2.setDuration(durationMillis);
        onBgView.startAnimation(an2);
    } else {
        offBgView.bringToFront();
        onBgView.setVisibility(View.VISIBLE);
        offBgView.setVisibility(View.VISIBLE);

        TranslateAnimation an1 = new TranslateAnimation(targetX, 0, 0, 0);
        an1.setFillAfter(true);
        an1.setDuration(durationMillis);
        circleView.startAnimation(an1);

        AlphaAnimation an2 = new AlphaAnimation(0, 1);
        an2.setFillAfter(true);
        an2.setDuration(durationMillis);
        offBgView.startAnimation(an2);
    }
}

兩個參數分別控制「目標狀態」與「是否需要動畫」。setFillAfter(true) 保留動畫終態,但不改變 View 本身的實際位置——這一點後面會談到它的隱患。切換時先 bringToFront() 把要顯示的背景提到最上層,再同時啟動位移與淡入。

二、SwitchButton 實現(二):純自定義繪製

這個樣式並不複雜,用基本圖形就能畫出來,而且不需要任何圖片資源。

繪制邏輯

先由自定義屬性確定按鈕整體大小與圓鈕大小;在 onMeasure 中約束測量值的 mode 與 size;在 onLayout 中算出圓角半徑與起點位置;最後依序繪製「底部 on 圓角矩形 → off 漸變縮放的圓角矩形 → 圓鈕」。

成員參數

public class SwitchButton extends View {

    private float radius;                              // 圓角半徑
    private int onColor = Color.parseColor("#4ebb7f");         // 開啟色
    private int offBorderColor = Color.parseColor("#dadbda");  // 關閉邊框色
    private int offColor = Color.parseColor("#ffffff");        // 關閉內部色
    private int spotColor = Color.parseColor("#ffffff");       // 手柄色
    private int borderColor = offBorderColor;
    private Paint paint;
    private boolean toggleOn = false;
    private int borderWidth = 2;
    private float centerY;                             // 垂直中心
    private float startX, endX;                        // 按鈕起止位置
    private float spotMinX, spotMaxX;                  // 手柄可移動範圍
    private int spotSize;
    private float spotX;                               // 手柄當前 x
    private float offLineWidth;                        // 關閉時內部灰帶高度
    private RectF rect = new RectF();
    private boolean defaultAnimate = true;
    private OnSwitchChanged listener;
}

測量與布局

onMeasure 的關鍵是:當寬高不是明確值(UNSPECIFIED / AT_MOST)時,給一個內置的明確尺寸,否則自定義 View 在 wrap_content 下會一無所有。

@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
    final int widthMode  = MeasureSpec.getMode(widthMeasureSpec);
    final int heightMode = MeasureSpec.getMode(heightMeasureSpec);
    int widthSize  = MeasureSpec.getSize(widthMeasureSpec);
    int heightSize = MeasureSpec.getSize(heightMeasureSpec);

    Resources r = Resources.getSystem();
    if (widthMode == MeasureSpec.UNSPECIFIED || widthMode == MeasureSpec.AT_MOST) {
        widthSize = (int) TypedValue.applyDimension(
                TypedValue.COMPLEX_UNIT_DIP, 50, r.getDisplayMetrics());
        widthMeasureSpec = MeasureSpec.makeMeasureSpec(widthSize, MeasureSpec.EXACTLY);
    }
    if (heightMode == MeasureSpec.UNSPECIFIED || heightMode == MeasureSpec.AT_MOST) {
        heightSize = (int) TypedValue.applyDimension(
                TypedValue.COMPLEX_UNIT_DIP, 30, r.getDisplayMetrics());
        heightMeasureSpec = MeasureSpec.makeMeasureSpec(heightSize, MeasureSpec.EXACTLY);
    }
    super.onMeasure(widthMeasureSpec, heightMeasureSpec);
}

@Override
protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
    super.onLayout(changed, left, top, right, bottom);
    final int width  = getWidth();
    final int height = getHeight();

    radius      = Math.min(width, height) * 0.5f;
    centerY     = radius;
    startX      = radius;
    endX        = width - radius;
    spotMinX    = startX + borderWidth;
    spotMaxX    = endX - borderWidth;
    spotSize    = height - 4 * borderWidth;
    spotX       = toggleOn ? spotMaxX : spotMinX;
    offLineWidth = 0;
}

繪制

@Override
public void draw(Canvas canvas) {
    // 1. 底部 on 背景
    rect.set(0, 0, getWidth(), getHeight());
    paint.setColor(borderColor);
    canvas.drawRoundRect(rect, radius, radius, paint);

    // 2. off 內部色帶(縮放到 0 時不畫)
    if (offLineWidth > 0) {
        final float cy = offLineWidth * 0.5f;
        rect.set(spotX - cy, centerY - cy, endX + cy, centerY + cy);
        paint.setColor(offColor);
        canvas.drawRoundRect(rect, cy, cy, paint);
    }

    // 3. 圓鈕外框
    rect.set(spotX - 1 - radius, centerY - radius,
             spotX + 1.1f + radius, centerY + radius);
    paint.setColor(borderColor);
    canvas.drawRoundRect(rect, radius, radius, paint);

    // 4. 圓鈕本體
    final float spotR = spotSize * 0.5f;
    rect.set(spotX - spotR, centerY - spotR, spotX + spotR, centerY + spotR);
    paint.setColor(spotColor);
    canvas.drawRoundRect(rect, spotR, spotR, paint);
}

狀態切換動畫

這裡有個取巧的寫法:用一個空的 Animation,靠 interpolatedTime(0~1 的插值)驅動重繪,達到逐帧過渡的效果,不必自己開線程或定時器。

/** animate 為 false 時直接跳到終態 */
private void takeEffect(boolean animate) {
    if (animate) {
        slide();
    } else {
        calculateEffect(toggleOn ? 1 : 0);
    }
}

private void slide() {
    Animation animation = new Animation() {
        @Override
        protected void applyTransformation(float interpolatedTime, Transformation t) {
            calculateEffect(toggleOn ? interpolatedTime : 1 - interpolatedTime);
        }
    };
    animation.setDuration(200);
    clearAnimation();
    startAnimation(animation);
}

/** 依 0~1 的進度值計算各項繪製參數 */
private void calculateEffect(final double value) {
    spotX = (float) mapValueFromRangeToRange(value, 0, 1, spotMinX, spotMaxX);
    offLineWidth = (float) mapValueFromRangeToRange(1 - value, 0, 1, 10, spotSize);

    // 依進度做 RGB 通道插值,實現顏色漸變
    int sb = clamp((int) mapValueFromRangeToRange(1 - value, 0, 1,
            Color.blue(onColor),  Color.blue(offBorderColor)),  0, 255);
    int sr = clamp((int) mapValueFromRangeToRange(1 - value, 0, 1,
            Color.red(onColor),    Color.red(offBorderColor)),   0, 255);
    int sg = clamp((int) mapValueFromRangeToRange(1 - value, 0, 1,
            Color.green(onColor),  Color.green(offBorderColor)), 0, 255);

    borderColor = Color.rgb(sr, sg, sb);
    postInvalidate();   // 請求下一次重繪
}

相較組合方案,純繪制版本更靈活、擴展性更好,也擺脫了對圖片資源的依賴——想換配色只要改幾個屬性,甚至能做成可按主題動態變化的樣式。

三、SegmentControl 實現

iOS 上常見的分段控制器,用來做同層級選項的互斥切換。這裡給出組合 View 的完整做法,並說明繪製思路。

思路一:View 組合

最省事的方案:用現成的 selector 與背景控制顯示效果,每個子項繼承 RelativeLayout 並實作 OnClick 監聽,最後由 SegmentView 統一控制選中態與點擊切換。

這裡出現三個值得說明的點:

· checkMode:選中模式,決定是 CHECKMODE_CHECK(複選、可 toggle)還是 CHECKMODE_RADIO(單選)。有了它,同一個自定義 Layout 就能同時勝任單選與複選。
· onInitializeAccessibilityEvent / NodeInfo:向外暴露 checked 狀態。由於事件可能由內部子 View 觸發,這裡要接收並處理,同時必須重寫 NodeInfo 補上 checkable 與 checked 資訊。
· SavedState:內部嵌套結構一複雜,旋轉螢幕就可能丟失狀態,因此需要自訂狀態保存類。

可點擊的通用 RelativeLayout 關鍵代碼:

// 定義 checked 狀態集合
public static final int[] CHECKED_STATE_SET = { android.R.attr.state_checked };

/** 依當前模式決定複選 toggle 還是單選 */
@Override
public boolean performClick() {
    if (checkMode == CHECKMODE_CHECK) {
        toggle();
    } else if (checkMode == CHECKMODE_RADIO) {
        setChecked(true);
    }
    return super.performClick();
}

/** 把 checked 狀態併入 drawable state,繪製時背景 selector 才會響應 */
@Override
public int[] onCreateDrawableState(int extraSpace) {
    int[] states = super.onCreateDrawableState(extraSpace + 1);
    if (isChecked()) {
        mergeDrawableStates(states, CHECKED_STATE_SET);
    }
    return states;
}

@Override
protected void drawableStateChanged() {
    super.drawableStateChanged();
    Drawable drawable = getBackground();
    if (drawable != null) {
        drawable.setState(getDrawableState());
        invalidate();
    }
}

@Override
public void onInitializeAccessibilityEvent(AccessibilityEvent event) {
    super.onInitializeAccessibilityEvent(event);
    event.setClassName(CheckedRelativeLayout.class.getName());
    event.setChecked(checked);
}

@Override
public void onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo info) {
    super.onInitializeAccessibilityNodeInfo(info);
    info.setClassName(CheckedRelativeLayout.class.getName());
    info.setCheckable(true);
    info.setChecked(checked);
}

狀態保存與恢復:

@Override
public Parcelable onSaveInstanceState() {
    Parcelable superState = super.onSaveInstanceState();
    SavedState ss = new SavedState(superState);
    ss.checked = isChecked();
    return ss;
}

@Override
public void onRestoreInstanceState(Parcelable state) {
    SavedState ss = (SavedState) state;
    super.onRestoreInstanceState(ss.getSuperState());
    setChecked(ss.checked);
    requestLayout();
}

static class SavedState extends BaseSavedState {
    boolean checked;

    SavedState(Parcelable superState) { super(superState); }

    private SavedState(Parcel in) {
        super(in);
        checked = (Boolean) in.readValue(null);
    }

    @Override
    public void writeToParcel(Parcel out, int flags) {
        super.writeToParcel(out, flags);
        out.writeValue(checked);
    }

    public static final Creator<SavedState> CREATOR = new Creator<SavedState>() {
        public SavedState createFromParcel(Parcel in) { return new SavedState(in); }
        public SavedState[] newArray(int size) { return new SavedState[size]; }
    };
}

SegmentView 本身邏輯直白:水平 LinearLayout 容納若干子項,依位置分別套用 left / center / right 背景;所有子項共用同一個監聽,點擊時取消其他項的選中態並觸發對外回呼。

protected CheckedRelativeLayout.OnCheckedChangeListener checkedChangeListener =
        new CheckedRelativeLayout.OnCheckedChangeListener() {
    @Override
    public void onCheckedChanged(CheckedRelativeLayout layout, boolean isChecked) {
        if (!isChecked) return;
        for (CheckedRelativeLayout item : checkedRelativeLayouts) {
            if (!item.equals(layout)) item.setChecked(false);
        }
        if (onIndexChangedListener != null) {
            index = indexOf(checkedRelativeLayouts, layout);
            onIndexChangedListener.onChanged(SegmentView.this, index);
        }
    }
};

這個方案的短處是配色定制性有限——只能靠既定 drawable。但其實 selector 內部完全可以用 shape 標籤自由定義漸變、圓角、描邊,發揮空間並不小。

思路二:自定義 View 繪制

核心要點兩步:

定義子 Item:自帶選中態、字色與背景色;在 onMeasure 中保證顯示範圍與字級;用 GradientDrawable 畫圓角背景,再 drawText 畫文字。這裡有個關鍵認知——XML 中 <shape> 產生的 drawable 物件,本質就是一個 GradientDrawable,所以代碼中直接 new 一個並呼叫 setCornerRadii(float[]),就能畫出與 XML 完全等效的效果,還能動態改色。

定義 Segment:繼承 ViewGroup,讀取自定義屬性並依文本內容建立子 View;重寫 onMeasure 與 onLayout 完成測量與定位;掛上點擊事件,對外提供監聽接口。

public class SegmentView extends ViewGroup implements OnClickListener {

    private final float r = TypedValue.applyDimension(
            TypedValue.COMPLEX_UNIT_DIP, 4, getResources().getDisplayMetrics());
    private int bgColor = 0xff0072c6;
    private int fgColor = Color.WHITE;
    private float mTextSize = 3f * r;
    private String[] mText = {"item1", "item2", "item3"};
    private int checkedItem = 1;
    private OnItemClickListener listener;

    protected void initFromAttributes(Context context, AttributeSet attrs) {
        if (attrs == null) return;
        TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.SegmentView0);
        String content = a.getString(R.styleable.SegmentView0_content0);
        if (!isEmpty(content)) {
            mText = content.split(",");
        }
        checkedItem = a.getInt(R.styleable.SegmentView0_index0, checkedItem);
        mTextSize = a.getDimension(R.styleable.SegmentView0_textSize0, mTextSize);
        bgColor = a.getColor(R.styleable.SegmentView0_bgColor, bgColor);
        fgColor = a.getColor(R.styleable.SegmentView0_textColor, fgColor);
        a.recycle();
    }

    /** 依選中態選擇背景色,交由 GradientDrawable 繪製 */
    private class ItemView extends View {
        private String text;
        private boolean isChecked;
        private int gravity;
        private GradientDrawable drawable;
        private Paint mTextPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
        private Rect mTextBound = new Rect();

        @Override
        protected void onDraw(Canvas canvas) {
            Rect rect = canvas.getClipBounds();
            drawable.setBounds(new Rect(rect));
            drawable.draw(canvas);

            // 依實際可用空間收縮字級,避免文字被裁切
            int width  = getMeasuredWidth();
            int height = getMeasuredHeight();
            float textSize = Math.min(mTextSize, height - 2 * r);
            if (width > 0) {
                textSize = Math.min(textSize, (width - 2 * r) * 2 / text.length());
            }
            if (textSize != mTextSize) {
                mTextPaint.setTextSize(textSize);
                mTextPaint.getTextBounds(text, 0, text.length(), mTextBound);
            }

            int l = (rect.width()  - mTextBound.width())  / 2;
            int b = (rect.height() + mTextBound.height()) / 2;
            canvas.drawText(text, l, b, mTextPaint);
        }
    }

    interface OnItemClickListener {
        void onItemClick(ItemView item, int checkedItem);
    }
}

四、一點反思

組合方案上手快、改動小,適合樣式固定且已有切圖資源的場景;繪製方案前期投入大,但换来的是完全的樣式控制權與更小的包體積。兩者並非新舊替代關係,取決於設計稿的複雜度與後續變更的頻率。

另外有個共同的坑值得記住:組合方案中 setFillAfter(true) 只保留動畫的視覺終態,並不改變 View 的實際位置。若在動畫未結束時發生重新佈局,圓鈕就會「彈回」原位。要根治,應在動畫結束後同步更新控件的真實狀態(例如切換背景或調整 LayoutParams),而不是長期依賴 fillAfter 撐著畫面。

同樣的東西用兩種思路各寫一遍,收穫往往比寫一遍多——你會被迫去想清楚「狀態到底存在哪裡」「誰負責繪製」「誰負責響應事件」這些問題。這大概就是重構帶來的隐性收益。

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