摘自:http://www.eoeandroid.com/thread-64029-1-1.html
我要做個表徵圖和文字結合的ListView,表徵圖資料也寫在了xml裡(見下方的arrays.xml)。但是輸出發現,這個
@drawable/latest不是id值,而是這個圖片的路徑值。我怎麼存放呢?以前的寫法是map.put("icon",
R.drawable.XXX); 就可以綁定表徵圖了...
簡短的代碼如下:
- String[] iconArr = getResources().getStringArray(R.array.feed_icons);
- String[] titleArr = getResources().getStringArray(R.array.feed_names);
- for(int i=0; i<iconArr.length; i++)
- {
- map = new HashMap<String, Object>();
- ImageView v = new ImageView(getContext());
- map.put("icon", iconArr[i]); //這樣寫是錯誤的:( 應該怎樣寫呢
- map.put("title", titleArr[i]);
- list.add(map);
- }
複製代碼
arrays.xml如下:
- <?xml version="1.0" encoding="utf-8"?>
- <resources>
-
- <string-array name="feed_names">
- <item>新聞</item>
- <item>視頻</item>
- <item>國際新聞</item>
- <item>體育</item>
- <item>藝術</item>
- <item>餐飲</item>
- </string-array>
-
- <string-array name="feed_icons">
- <item>@drawable/latest</item>
- <item>@drawable/video</item>
- <item>@drawable/world</item>
- <item>@drawable/sports</item>
- <item>@drawable/arts</item>
- <item>@drawable/dining</item>
- </string-array>
- </resources>
複製代碼
解決方案:
特別感謝LuoYer
- Map<String, Object> map;
- TypedArray ta = getResources().obtainTypedArray(R.array.feed_icons);
- String[] titleArr = getResources().getStringArray(R.array.feed_names);
- for(int i=0; i<titleArr.length; i++)
- {
- map = new HashMap<String, Object>();
- map.put("icon", ta.getResourceId(i, 0));
- map.put("title", titleArr[i]);
- list.add(map);
- }
複製代碼
============================ private void initAdapters(Context context) {
TypedArray mainNavIcon = context.getResources().obtainTypedArray(R.array.mainNavIcon);
String[] mainNav = context.getResources().getStringArray(R.array.mainNav);
mHomeAdapter = new PopupIconTextAdapter(context);
for (int i = 0; i < mainNav.length; i++) {
mHomeAdapter.add(getIconTextListItem(context, mainNavIcon.getResourceId(i, 0), mainNav[i]));
}
}
private IconTextListItem getIconTextListItem(Context context, int mainNavIcon, String mainNavText) {
IconTextListItem iconText = new IconTextListItem(context.getResources().getDrawable(
mainNavIcon), mainNavText);
return iconText;
}