简体   繁体   English

java android getResources()。getIdentifier()

[英]java android getResources().getIdentifier()

How do I get the int id value from R. for an id? 如何从R获取id的int id值? When I use getIdentifier its just returns 0 . 当我使用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());

Edit 编辑

Xml 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>

log 日志

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

The problem appears to be that you are converting drawerSelection to lower case. 问题似乎是您将drawerSelection转换为小写。 As is clear in the R.java file, the case of the identifier is preserved. 从R.java文件中可以清楚地看出,标识符的大小写是保留的。 Try calling: 试着打电话:

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

Just checked back in a project I'm writing right now: 刚刚回过头来看我正在写的项目:

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

getResources returns int . getResources返回int

UPDATE: Check R.array.drawerSelection_array to include only ID's of existing elements. 更新:检查R.array.drawerSelection_array以仅包含现有元素的ID。

Try this method. 试试这个方法。

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

Calling 调用

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM