Integer array of resource ids returns 0

柔情痞子 提交于 2019-12-06 03:27:43

问题


I have a set of resource ids stored in an array. This is accessed inside the recycler view to populate an image view. The problem is when I access the array, all values returned is 0.

// arrays.xml
<array name="array_category_icons">
    <item>@drawable/autumn</item>
    <item>@drawable/backpack</item>
</array>

// inside recycler view adapter
int[] myIcons = getActivity().getResources().getIntArray(R.array.array_category_icons);

myIcons[i] always returns 0. 

The drawables are in the hdpi folder only.


回答1:


Do this:

TypedArray ta = getResources().obtainTypedArray(R.array.array_category_icons);
Drawable[] icons = new Drawable[ta.length()];
for (int i = 0; i < ta.length(); i++) {
    int id = ta.getResourceId(i, 0);
    if (id != 0) {
        icons[i] = ContextCompat.getDrawable(this, id);
    }
}
ta.recycle();


来源:https://stackoverflow.com/questions/43307243/integer-array-of-resource-ids-returns-0

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