Error: Expected resource of type styleable [ResourceType] error

僤鯓⒐⒋嵵緔 提交于 2019-12-04 15:15:28

问题


Take a look at this code snippet. I am getting an error with the last line, because I am passing an 'index' instead of a resource. I thought it was a lint issue and tried to suppress it. Then I noticed I am getting this error only when I building for release. It works fine when building for debug. I am totally clueless. Can anyone throw some light into what I am doing wrong.

//Get paddingLeft, paddingRight
        int[] attrsArray = new int[]{
                android.R.attr.paddingLeft,  // 0
                android.R.attr.paddingRight, // 1
        };
        TypedArray ta = context.obtainStyledAttributes(attrs, attrsArray);
        if (ta == null) return;
        mPaddingLeft = ta.getDimensionPixelSize(0, 0);
        mPaddingRight = ta.getDimensionPixelSize(1/*error here*/, 0); 

回答1:


I had the same issue when trying to build a signed apk. Solved it by adding @SuppressWarnings("ResourceType") to suppress the warning, now it works fine.




回答2:


@StyleableRes int index = 1;

mPaddingRight = ta.getDimensionPixelSize(index, 0); 



回答3:


So the way I fixed this in Kotlin is the following: (thanks to Simons post)

companion object {
    private val attributes = intArrayOf(
            android.R.attr.paddingLeft,
            android.R.attr.paddingTop,
            android.R.attr.paddingBottom,
            android.R.attr.paddingRight)
}

init {
    val arr = context.obtainStyledAttributes(attrs, attributes)

    @StyleableRes
    var i = 0

    val leftPadding = arr.getDimensionPixelOffset(i++, 0)
    val topPadding = arr.getDimensionPixelOffset(i++, 0)
    val rightPadding = arr.getDimensionPixelOffset(i++, 0)
    val bottomPadding = arr.getDimensionPixelOffset(i, 0)

    arr.recycle()
}



回答4:


TypedValue outValue = new TypedValue();
context.getTheme().resolveAttribute(android.R.attr.paddingLeft, outValue, true);
int paddingLeft = outValue.data;

Repeat the same for android.R.attr.paddingRight



来源:https://stackoverflow.com/questions/36254914/error-expected-resource-of-type-styleable-resourcetype-error

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!