2010-06-15 50 views

回答

245

像這樣的東西:

String mDrawableName = "myappicon"; 
int resID = getResources().getIdentifier(mDrawableName , "drawable", getPackageName()); 
+10

謝謝,這幫助我找到一個解決方案,以解決simliar問題!我將使用getResources()。getIdentifier(name,「id」,getPackageName());'獲取ImageButton的ID(與使用R.id.name一樣)。 – Select0r 2010-07-26 19:19:36

+38

請注意,可繪製名稱不應包含像「.png」這樣的擴展名 – larham1 2011-08-18 18:17:57

+9

此答案應標記爲接受。 – 2012-07-24 11:59:06

26

你也可以試試這個:

try { 
    Class res = R.drawable.class; 
    Field field = res.getField("drawableName"); 
    int drawableId = field.getInt(null); 
} 
catch (Exception e) { 
    Log.e("MyTag", "Failure to get drawable id.", e); 
} 

我從以下網址複製本的源代碼。基於本頁面所做的測試,它比getIdentifier()快5倍。我還發現它更方便和易於使用。希望它也能幫助你。

鏈接:Dynamically Retrieving Resources in Android

+1

這可能會更快,但是如果使用proguard,我發現它可能會讓您陷入麻煩。至少對我而言,這在proguard中不起作用 – 2012-03-13 21:52:01

+0

這個getResources()。getIdentifier與proguard – 2012-03-13 21:52:30

+0

一起使用感謝您的通知:) – VSB 2013-06-28 13:51:29

9

您可以使用此功能來獲取資源ID:如果你想獲得一個可繪製資源ID

public static int getResourseId(Context context, String pVariableName, String pResourcename, String pPackageName) throws RuntimeException { 
    try { 
     return context.getResources().getIdentifier(pVariableName, pResourcename, pPackageName); 
    } catch (Exception e) { 
     throw new RuntimeException("Error getting Resource ID.", e) 
    } 
} 


所以,你可以這樣調用方法:

getResourseId(MyActivity.this, "myIcon", "drawable", getPackageName()); 

(或片段):

getResourseId(getActivity(), "myIcon", "drawable", getActivity().getPackageName()); 


對於字符串資源ID,你可以這樣調用:

getResourseId(getActivity(), "myAppName", "string", getActivity().getPackageName()); 

等等


小心:如果無法找到資源ID,則會引發RuntimeException。一定要在生產中恢復正常。

用於公共系統資源

Read this

+4

我認爲你需要從中刪除'static',否則'getResources()'會不行。 – 2014-05-09 08:48:44

+0

@Richard Le Mesurier,你能解釋一下爲什麼嗎?謝謝。 – 2016-08-26 04:27:33

+1

@ Leo.Han當我發表評論時,「Context」不可用。 Fix要麼刪除'static'並將其移入'Context'(例如'Activity'或'Application');或者替代修正是喬納森在編輯中所做的,即將「上下文」傳遞給該方法。 – 2016-08-26 06:48:36

10

實施例:

// this will get id for android.R.drawable.ic_dialog_alert 
int id = Resources.getSystem().getIdentifier("ic_dialog_alert", "drawable", "android"); 

alert

另一種方法是參考的文檔android.R.drawable類。

+0

this是真的,但必須訪問正確的上下文 – Milaaaad 2016-01-18 09:48:28

+1

@Milaaaad你是什麼意思? – naXa 2016-01-18 10:08:57

+0

這意味着我被代碼 中的資源困惑,我將它用於非活動類 – Milaaaad 2016-01-19 07:07:47

0

我遇到的另一種情況。

String imageName =「Hello」 然後當它傳入 getIdentifier函數作爲第一個參數時,它將傳遞帶有字符串null終止的名稱並始終返回零。 通過這個 imageName.substring(0,imageName.length() - 1)

相關問題