Java android getResources(). getIdentifier()
Как получить значение идентификатора int из R. для 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());
Edit
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;
Ответы
Ответ 1
Проблема заключается в том, что вы конвертируете drawerSelection
в нижний регистр. Как видно из файла R.java, регистр идентификатора сохраняется. Попробуйте позвонить:
int panelId = this.getResources().getIdentifier(drawerSelection,"id",getActivity().getPackageName());
Ответ 2
Только что вернулась в проект, который я пишу прямо сейчас:
int id = getResources().getIdentifier("resourcename", "drawable", getPackageName());
getResources
возвращает int
.
UPDATE: установите флажок R.array.drawerSelection_array
, чтобы включить только идентификатор существующих элементов.
Ответ 3
Попробуйте этот метод.
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);