2013-05-31 86 views
11

如何從R獲取int id值來獲取id?當我使用getIdentifier時,它僅返回0java android getResources()。getIdentifier()

int i = getArguments().getInt(SELECTION_NUMBER); 
String drawerSelection = getResources().getStringArray(R.array.drawerSelection_array)[i]; 

int panelId = this.getResources().getIdentifier(drawerSelection.toLowerCase(),"id",getActivity().getPackageName()); 

編輯

的Xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
android:layout_width="match_parent" 
android:layout_height="match_parent" 
android:orientation="vertical" > 

<ListView 
    android:id="@+id/Bus_Schedules" 
    android:layout_width="match_parent" 
    android:layout_height="wrap_content" > 
</ListView> 

</LinearLayout> 

日誌

06-10 21:24:30.372: I/System.out(3572): Selection = Bus_Schedules 
06-10 21:24:30.372: I/System.out(3572): panelId = 0 

R.java

public static final class id { 
    public static final int Bus_Schedules=0x7f090004; 
    public static final int basemenu=0x7f090005; 
    public static final int content_frame=0x7f090001; 
    public static final int drawer_layout=0x7f090000; 
    public static final int left_drawer=0x7f090002; 

int id = getResources().getIdentifier("resourcename", "drawable", getPackageName()); 

getResources回報int

+0

當它返回0時,表示沒有找到id。 'drawerSelection'的價值是什麼?你確認你有一個用這個名字定義的id資源嗎? –

+0

您需要發佈一些關於該問題的更多信息以獲得更好的回覆。使用調試器(或一個日誌語句)來確定'drawerSelection'具體的值。將適用的XML定義爲資源。 (順便說一句,你可以在'toLowerCase'的調用中省略默認的區域設置參數;這就是它會使用它的地方,它只是混亂了你的代碼。) –

回答

17

這個問題似乎是要轉換drawerSelection爲小寫。正如R.java文件中清楚的那樣,標識符的情況被保留。嘗試撥打:

int panelId = this.getResources().getIdentifier(drawerSelection,"id",getActivity().getPackageName()); 
7

在一個項目中,我正在寫,現在就籤回。

更新:檢查R.array.drawerSelection_array以僅包含現有元素的ID。

+0

這並沒有回答這個問題。它也爲OP返回一個int。 OP的問題是int爲0. –

+0

謝謝,我會編輯我的答案。 –

+0

「更新:檢查R.array.drawerSelection_array以僅包含現有元素的ID。」 ?????? – Spik330

-1

試試這種方法。

public static int getResId(String fieldName, Context context, Class<?> c) { 

    try { 
     Field field= c.getDeclaredField(fieldName); 
     return field.getInt(field); 
    } catch (Exception e) { 
     return 0; 
    } 
} 

調用

//edtUserName is my field id 
getResId("edtUserName", context, id.class); 
+0

即時通訊不使用上下文即時通訊使用LayoutInflater和ViewGroup – Spik330

+0

並且它無法理解該語句中的內容。 – Spik330

+0

上下文是您的應用程序基礎上下文。只需將它作爲getApplicationContext(); – Adnan

相關問題