Resource arrays [duplicate]

2019-03-09 18:47发布

This question already has an answer here:

Is there a way to define an array in XML in which the elements are resource references? For example (it doesn't work, but it explains what I want):

<integer-array name="actions_images">
    <item>@drawable/pencil</item>
    <item>@drawable/pencil</item>
    <item>@drawable/pencil</item>
    <item>@drawable/pencil</item>
    <item>@drawable/pencil</item>
    <item>@drawable/pencil</item>
</integer-array>

1条回答
别忘想泡老子
2楼-- · 2019-03-09 19:26

If I understand your question correctly, I think I know a workaround (since accessing them via getResources().getIntArray() doesn't work). (You can read more here, that is the source I took the workaround from.)

TypedArray ar = context.getResources().obtainTypedArray(R.array.my_array);
int len = ar.length();     
int[] resIds = new int[len];     
for (int i = 0; i < len; i++)     
    resIds[i] = ar.getResourceId(i, 0);

ar.recycle();                       
// Do stuff with resolved reference array, resIds[]...     
for (int i = 0; i < len; i++)     
    Log.v (TAG, "Res Id " + i + " is " + Integer.toHexString(resIds[i]));
查看更多
登录 后发表回答