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

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_37063860/article/details/82585859

最近开发时获取自定义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)

成功运行。

猜你喜欢

转载自blog.csdn.net/qq_37063860/article/details/82585859