13

如何从 R. 获取 int id 值以获得 id?当我使用它时,getIdentifier它只是返回0

 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;
4

3 回答 3

25

问题似乎是您正在转换drawerSelection为小写。正如 R.java 文件中清楚的那样,标识符的大小写被保留。尝试调用:

int panelId = this.getResources().getIdentifier(drawerSelection,"id",getActivity().getPackageName());
于 2013-06-11T18:18:22.293 回答
9

刚刚检查了我现在正在写的一个项目:

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

getResources返回int

更新:检查R.array.drawerSelection_array以仅包含现有元素的 ID。

于 2013-05-31T16:41:23.883 回答
-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);
于 2013-05-31T17:04:39.923 回答