ImageView.setSelected 设置状态时候发现图片变大的问题

298 阅读1分钟
<ImageView
    android:id="@+id/ivReadView"
    android:layout_width="wrap_content"
    android:layout_height="@dimen/dp_18"
    android:src="@drawable/ic_check_src"
    android:layout_marginLeft="@dimen/dp_10"
    />

ic_check_src.xml文件

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:drawable="@mipmap/check" android:state_selected="true" />
    <item android:drawable="@mipmap/uncheck" />
</selector>

在代码里面设置: ivReadView.setSelected(true)的时候发现图标会变大 进入setSelected方法查看一下源码

public void setSelected(boolean selected) {
    super.setSelected(selected);
    //调整图片的大小
    resizeFromDrawable();
}

进入resizeFromDrawable方法:

private void resizeFromDrawable() {
    final Drawable d = mDrawable;
    if (d != null) {
        int w = d.getIntrinsicWidth();
        if (w < 0) w = mDrawableWidth;
        int h = d.getIntrinsicHeight();
        if (h < 0) h = mDrawableHeight;
        if (w != mDrawableWidth || h != mDrawableHeight) {
            mDrawableWidth = w;
            mDrawableHeight = h;
            requestLayout();
        }
    }
}

进入getIntrinsicWidth和getIntrinsicHeight


/**
 * Returns the drawable's intrinsic width.
 * <p>
 * Intrinsic width is the width at which the drawable would like to be laid
 * out, including any inherent padding. If the drawable has no intrinsic
 * width, such as a solid color, this method returns -1.
 *
 * @return the intrinsic width, or -1 if no intrinsic width
 */
public int getIntrinsicWidth() {
    return -1;
}

/**
 * Returns the drawable's intrinsic height.
 * <p>
 * Intrinsic height is the height at which the drawable would like to be
 * laid out, including any inherent padding. If the drawable has no
 * intrinsic height, such as a solid color, this method returns -1.
 *
 * @return the intrinsic height, or -1 if no intrinsic height
 */
public int getIntrinsicHeight() {
    return -1;
}

发现在requestLayout的时候大小变成了图片的大小,所以变大啦(在低分辩系统上显示的就是图片的大小)

解决办法 -〉设置控件的宽高