1. 程式人生 > >(Android日常)從.xml中獲取陣列中的@drawable

(Android日常)從.xml中獲取陣列中的@drawable

在寫APP時,想從.xml中獲取@drawable/picname

Resources res = getResources();
int[] imageId = res.getIntArray(R.array.bookImage);
  • 然後用Log.i監視值結果
    07-09 21:34:34.809 11010-11010/com.three.learning I/image: 0
    07-09 21:34:34.809 11010-11010/com.three.learning I/image: 0
    07-09 21:34:34.809 11010-11010/com.three.learning I/image: 0
    07-09 21:34:34.809 11010-11010/com.three.learning I/image: 0
    07-09 21:34:34.809 11010-11010/com.three.learning I/image: 0
    07-09 21:34:34.809 11010-11010/com.three.learning I/image: 0

最後,StackOverFlow 給出的答案是

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

ar.recycle();