Can't convert value at index 11 to dimension:type=0x10

最近开发时获取自定义layout_width、layout_height属性时报如下错误:

Caused by: java.lang.UnsupportedOperationException: Can't convert value at index 11 to dimension: type=0x10
        at android.content.res.TypedArray.getDimension(TypedArray.java:621)
        at com.demo.cjh.myapplication.LoadingLayout.<init>(LoadingLayout.kt:147)

不能将获取的值转换成dimension类型,

打开出错代码:

errorImageWidth = a.getDimension(R.styleable.LoadingLayout_errorImage_layout_width,-2f).toInt()
errorImageHight = a.getDimension(R.styleable.LoadingLayout_errorImage_layout_height,-2f).toInt()

获取控件宽度值的时候出错了,因为xml文件我填的是:

app:errorImage_layout_width="wrap_content"
app:errorImage_layout_height="wrap_content"

也就是说不能获取枚举好的值,验证发现固定值如80dp是可以正常获取的,纠结了大半天,查看ImageView源码发现ImageView的宽度属性是ViewGroup.LayoutParams类型中的,打开ViewGroup.LayoutParams看到构造函数:

public LayoutParams(Context c, AttributeSet attrs) {
    TypedArray a = c.obtainStyledAttributes(attrs, R.styleable.ViewGroup_Layout);
    setBaseAttributes(a,
            R.styleable.ViewGroup_Layout_layout_width,
            R.styleable.ViewGroup_Layout_layout_height);
    a.recycle();
}

可以发现ViewGroup的长宽是setBaseAttributes函数获取的,而setBaseAttributes的内容是:

protected void setBaseAttributes(TypedArray a, int widthAttr, int heightAttr) {
    width = a.getLayoutDimension(widthAttr, "layout_width");
    height = a.getLayoutDimension(heightAttr, "layout_height");
}

由此可知长宽的类型获得是TypedArray中的getLayoutDimension函数,而我使用的是getDimension,该函数只能获取一般固定值,layout有特殊函数获取,将代码改为:

errorImageWidth = a.getLayoutDimension(R.styleable.LoadingLayout_errorImage_layout_width,-2)
errorImageHight = a.getLayoutDimension(R.styleable.LoadingLayout_errorImage_layout_height,-2)

成功运行。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值