自定義CheckBox樣式

drawable目錄下新建selector_checkbox.xml文件,指定自定義的樣式

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
  <item android:drawable="@drawable/check_selected_blue" android:state_checked="true"/>
  <item android:drawable="@drawable/check_unselected" android:state_checked="false"/>
  <item android:drawable="@drawable/check_unselected"/>
</selector>

values/styles.xml中定義CustomCheckBox樣式,由于自定義樣式一般是使用圖片素材,如果使用android:button則會(huì)發(fā)生圖片尺寸無法自適應(yīng)的問題,導(dǎo)致在不同機(jī)型上顯示效果不一,主要是因?yàn)?code>mBackgroundDrawable和mButtonDrawable的尺寸計(jì)算不一樣,mBackgroundDrawable采用的是view的寬高進(jìn)行繪制,而mBackgroundDrawable使用的是本身的固有寬高,即圖片的固有寬高進(jìn)行繪制,所以不會(huì)隨著view的尺寸而自適應(yīng)。

mButtonDrawable繪制:
    @Override
    protected void onDraw(Canvas canvas) {
        final Drawable buttonDrawable = mButtonDrawable;
        if (buttonDrawable != null) {
            final int verticalGravity = getGravity() & Gravity.VERTICAL_GRAVITY_MASK;
            final int drawableHeight = buttonDrawable.getIntrinsicHeight();
            final int drawableWidth = buttonDrawable.getIntrinsicWidth();

            final int top;
            switch (verticalGravity) {
                case Gravity.BOTTOM:
                    top = getHeight() - drawableHeight;
                    break;
                case Gravity.CENTER_VERTICAL:
                    top = (getHeight() - drawableHeight) / 2;
                    break;
                default:
                    top = 0;
            }
            final int bottom = top + drawableHeight;
            final int left = isLayoutRtl() ? getWidth() - drawableWidth : 0;
            final int right = isLayoutRtl() ? getWidth() : drawableWidth;

            buttonDrawable.setBounds(left, top, right, bottom);
        }

mBackground繪制:
   private void drawBackground(Canvas canvas) {
        final Drawable background = mBackground;
        if (background == null) {
            return;
        }

        setBackgroundBounds();
        ...
    }
    void setBackgroundBounds() {
        if (mBackgroundSizeChanged && mBackground != null) {
            mBackground.setBounds(0, 0, mRight - mLeft, mBottom - mTop);
            mBackgroundSizeChanged = false;
            rebuildOutline();
        }
    }

因此采用android:background替換android:button,完美解決圖片尺寸自適應(yīng)問題

<style name="CustomCheckBox" parent="@android:style/Widget.CompoundButton.CheckBox">
    <item name="android:button">@null</item>
    <item name="android:background">@drawable/selector_checkbox</item>
</style>

最后在代碼中指定style即可

<CheckBox
      style="@style/MangatoonCheckBox"
      android:layout_width="20dp"
      android:layout_height="20dp"/>
image.png
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容