[英]How to get resource id from String
我有一個帶有圖像名稱列表的數據庫列。 我想使用setImageResource將其放在imageview中。 在我的其他應用程序中,我設法做到了這一點,但是在此應用程序中,imageview根本不顯示任何內容。
String Image1 = db.getImage1Now(RandomIndex);
imageViewDoThis1.setImageResource(getResources().getIdentifier( Image1, "drawable", getPackageName()));
如果我這樣做:
imageViewDoThis1.setImageResource(R.drawable.image1);
然后就可以了。
用這個:
imageViewDoThis1.setImageResource(getResources().getIdentifier( "image1", "drawable", getPackageName()));
我認為getIdentifier
應該以字符串作為第一個參數。
所以我有一個與此非常相似的問題。
我的資源中有一堆圖像,我希望能夠存儲數據庫中屬於每個項目的圖像。 我最終在數據庫中使用了商品的ID作為圖像的唯一標識符。 這些ID對應於我的DbIcons類中的常量。 當我構造所需的任何對象時,我從該幫助程序類中檢索了資源ID。
當我想檢索正確的圖像時,我將從數據庫中獲取ID,然后調用靜態方法getIcon(categoryId)。 這將返回R.id值,並將其傳遞給ImageView。
這是我的代碼片段。 為了簡短起見,我刪除了大多數變量和switch語句:
public Category(int id) { this.id = id; this.name = ""; this.icon = null; this.iconResourceId = DbIcons.getIcon(id); this.plateIconResourceId = DbIcons.getPlateIcon(id); }
public class DbIcons { /* Category Ids */ private final static int CAT_BABY = 1; private final static int CAT_BAKED_GOODS = 2; private final static int CAT_BAKING = 3; /* Plate Ids */ private final static int PLATE_BABY = 1; private final static int PLATE_BAKED_GOODS = 2; private final static int PLATE_BAKING = 3; public static int getIcon(int cat) { switch (cat) { case CAT_BABY: return R.drawable.baby; case CAT_BAKED_GOODS: return R.drawable.bakedgoods; case CAT_BAKING: return R.drawable.baking; } return R.drawable.default; } public static int getPlateIcon(int plateIcon) { switch (plateIcon) { case PLATE_BABY: return R.drawable.baby_plate; case PLATE_BAKED_GOODS: return R.drawable.bakedgoods_plate; case PLATE_BAKING: return R.drawable.baking_plate; } return R.drawable.default; } }
我希望這是有道理的,對您有所幫助。 如果您想讓我澄清更多,請問。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.