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