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
则会发生图片尺寸无法自适应的问题,导致在不同机型上显示效果不一,主要是因为mBackgroundDrawable
和mButtonDrawable
的尺寸计算不一样,mBackgroundDrawable
采用的是view
的宽高进行绘制,而mBackgroundDrawable
使用的是本身的固有宽高,即图片的固有宽高进行绘制,所以不会随着view
的尺寸而自适应。
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
,完美解决图片尺寸自适应问题
<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
网友评论