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

自定義帶數字角標的 CheckBox:selector 與自定義 View 兩種實作

編輯:關於 Android 程式設計

近期手上的專案一直在做即時通訊,聊天功能裡「發圖片」幾乎是標配。既然要做,不妨先看看成熟產品是怎麼處理的——打開 QQ 走一遍選圖流程,會發現每張縮圖的右上角都掛著一個小圓標,圓標裡寫著目前已經選了幾張。這個細節很小,卻讓「已選數量」一目了然。

於是我就動手仿了一版,做到選圖標記時順便有個念頭:與其堆一堆 TextView 和背景圖,不如自己寫一個 View 把這件事收乾淨。當然,用 selector 加 shape 也能拼出來,下面會先示範這種最省事的做法,再進入自定義控件的版本。先來看最終效果:

第一種:selector + shape

思路很直接:幫 TextView 準備兩組橢圓背景,用 state_enabled 切換「已選」與「未選」的樣式,數字則直接寫在 text 裡。

photo_selector.xml:

<selector xmlns:android="https://schemas.android.com/apk/res/android">
    <item android:state_enabled="true">
        <shape android:shape="oval">
            <stroke android:color="#FFFFFF" android:width="1dp" />
            <solid android:color="@color/title_bg" />
        </shape>
    </item>
    <item android:state_enabled="false">
        <shape android:shape="oval">
            <stroke android:color="@color/white" android:width="1dp" />
            <solid android:color="@color/half_trans_bg" />
        </shape>
    </item>
</selector>

佈局中的 TextView:

<TextView
    android:id="@+id/tv_point"
    android:layout_width="30dp"
    android:layout_height="30dp"
    android:background="@drawable/photo_selector"
    android:clickable="true"
    android:gravity="center"
    android:text="1"
    android:textColor="#FFFFFF" />

Activity 中的測試碼:

tv = (TextView) findViewById(R.id.tv_point);

public void click1(View v) {
    tv.setEnabled(true);
    tv.setText("4");
}

public void click2(View v) {
    tv.setEnabled(false);
    tv.setText("");
}

兩個按鈕分別負責「選中」和「取消選中」,基本效果確實出來了。但真實場景通常不是這樣:使用者點的往往就是那個圓標本身。一旦掛上點擊監聽,問題就來了——按下之後再也按不動,因為 enabled 狀態被自己的回呼改掉,後續事件就不再進來。

tv.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        if (tv.isEnabled()) {
            tv.setEnabled(false);
    } else {
            tv.setEnabled(true);
        }
    }
});

也就是說,selector 這條路很輕巧,卻把「狀態」和「可點擊性」綁在了一起,想讓點自己也能切換就別扭了。要徹底解耦,還是得自己畫。

第二種:自定義 View

效果如下:

① 定義自定義屬性

把背景色、文字色、描邊、半徑、文字大小都開成 XML 屬性,方便在不同頁面複用同一個控件。

TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.NumberSelectView);
mBackgroundColorNormal = typedArray.getColor(R.styleable.NumberSelectView_backgroundColorNormal, Color.parseColor("#33000000"));
mBackgroundColorSelect = typedArray.getColor(R.styleable.NumberSelectView_getBackgroundColorSelect, Color.parseColor("#ff5f62"));
mTextColor = typedArray.getColor(R.styleable.NumberSelectView_textColor, Color.parseColor("#FFFFFF"));
mStrokeColor = typedArray.getColor(R.styleable.NumberSelectView_strokeColor, Color.parseColor("#66FFFFFF"));
mStrokeWidth = typedArray.getDimension(R.styleable.NumberSelectView_strokeWidth, UIUtils.dp2px(context, 2.0f));
mSolidRadius = typedArray.getDimension(R.styleable.NumberSelectView_solidRadius, UIUtils.dp2px(context, 15.0f));
mTextSize = typedArray.getDimension(R.styleable.NumberSelectView_textSize, UIUtils.sp2px(context, 14.0f));
text = typedArray.getString(R.styleable.NumberSelectView_text);
typedArray.recycle(); // 記得回收

attr.xml:

<resources>
    <declare-styleable name="NumberSelectView">
        <attr name="backgroundColorNormal" format="color" />
        <attr name="getBackgroundColorSelect" format="color" />
        <attr name="textColor" format="color" />
        <attr name="strokeColor" format="color" />
        <attr name="strokeWidth" format="dimension" />
        <attr name="solidRadius" format="dimension" />
        <attr name="textSize" format="dimension" />
        <attr name="text" format="string" />
    </declare-styleable>
</resources>

② 重寫 onMeasure

這個控件本質是個正圓,尺寸必須自己算死:直徑 =(實心圓半徑 + 描邊寬度)× 2,再把 padding 加回來。

@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
    int exceptWidth = (int) ((mSolidRadius + mStrokeWidth) * 2) + getPaddingLeft() + getPaddingRight();
    int exceptHeight = (int) ((mSolidRadius + mStrokeWidth) * 2) + getPaddingTop() + getPaddingBottom();
    widthMeasureSpec = MeasureSpec.makeMeasureSpec(exceptWidth, MeasureSpec.EXACTLY);
    heightMeasureSpec = MeasureSpec.makeMeasureSpec(exceptHeight, MeasureSpec.EXACTLY);
    super.onMeasure(widthMeasureSpec, heightMeasureSpec);
}

③ 重寫 onDraw

把繪製拆成三個小方法,各管一件事,可讀性會好很多。

@Override
protected void onDraw(Canvas canvas) {
    drawCircle(canvas); // 實心圓
    drawRing(canvas);   // 外圈圓環
    drawText(canvas);   // 數字
}

// 實心圓:未選中用自己的底色,選中時換成高亮色
private void drawCircle(Canvas canvas) {
    if (!isSelected) {
        canvas.drawCircle(mCenterX, mCenterY, mSolidRadius, mSolidPaint);
    } else {
        mSolidPaint.setColor(mBackgroundColorSelect);
        canvas.drawCircle(mCenterX, mCenterY, mSolidRadius, mSolidPaint);
        mSolidPaint.setColor(mBackgroundColorNormal);
    }
}

// 圓環:用 drawArc 掃滿 360 度
private void drawRing(Canvas canvas) {
    RectF rectF = new RectF();
    rectF.top = mCenterY - mRingRadius;
    rectF.bottom = mCenterY + mRingRadius;
    rectF.left = mCenterX - mRingRadius;
    rectF.right = mCenterX + mRingRadius;
    canvas.drawArc(rectF, 0, 360, false, mStrokePaint);
}

// 文字:靠文字實際邊距做置中,避免視覺偏移
private void drawText(Canvas canvas) {
    Rect bounds = new Rect();
    mTextPaint.getTextBounds(text, 0, text.length(), bounds);
    float x = (getMeasuredWidth() - bounds.width()) / 2;
    float y = (getMeasuredHeight() + bounds.height()) / 2;
    if (isSelected) {
        canvas.drawText(text, x, y, mTextPaint);
    } else {
        canvas.drawText("", x, y, mTextPaint);
    }
}

④ 初始化

這裡有個關鍵設計:把「是否選中」當成獨立狀態,點擊只呼叫 toggle() 翻轉狀態並 invalidate(),完全不碰 enabled。這樣點自己也能自由切換,正是 selector 方案卡住的地方。

private void init() {
    if (TextUtils.isEmpty(text)) {
        text = "1";
    }
    mRingRadius = mSolidRadius + mStrokeWidth / 2;
    setClickable(true);
    setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {
            if (listener != null) {
                listener.onClick(isSelected);
            }
            toggle();
        }
    });
    mStrokePaint = new Paint(Paint.ANTI_ALIAS_FLAG);
    mStrokePaint.setColor(mStrokeColor);
    mStrokePaint.setStyle(Paint.Style.STROKE);
    mStrokePaint.setStrokeWidth(mStrokeWidth);

    mSolidPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
    mSolidPaint.setColor(mBackgroundColorNormal);
    mSolidPaint.setStyle(Paint.Style.FILL);

    mTextPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
    mTextPaint.setColor(mTextColor);
    mTextPaint.setTextSize(mTextSize);
}

private void toggle() {
    isSelected = !isSelected;
    invalidate();
}

@Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
    mCenterX = w / 2;
    mCenterY = h / 2;
}

⑤ 對外開放的 API

外部既要能讀,也要能寫。特別是「不傳點擊、直接依數字判定選中狀態」這種由資料反推 UI 的場景,很常見。

public void setViewText(String text, boolean isViewClick) {
    this.text = text;
    if (!isViewClick) {
        isSelected = !TextUtils.isEmpty(text);
    }
    invalidate();
}

public String getViewText() {
    return text;
}

public boolean isViewSelected() {
    return isSelected;
}

public interface OnOnStateChangeListener {
    void onClick(boolean isSelected);
}

小結

兩種做法各有適用範圍。若只是幾個固定位置的角標,selector 幾行 XML 就能搞定;一旦需要「點擊自身切換」、「外部資料驅動狀態」或反覆複用,自定義 View 把狀態與樣式都握在自己手裡,反而更省心。核心心得只有一句:狀態獨立於 enabled,繪製與狀態解耦。

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