Android 将字符串名称转换为 R.drawable.name
Android Cast String name to R.drawable.name
在我的 android 应用程序中,我需要在 class MyAdapter
中创建一个函数,它在 Activity MyActivity
中使用(这是不是 MainActivity
)。该函数应具有以下结构
public int getDrawableResourceId(String name) {
// naive explanation
return R.drawable. + name
}
例如,如果我调用 getDrawableResorceId("test")
,它应该 return R.drawable.test
的整数值。我无法使用 int drawableResourceId = getResources().getIdentifier(name, "drawable", getPackageName());
,因为 Android Studio 告诉我无法解析方法 getResources()
和 getPackageName()
。如果我用
替换它
int drawableResourceId = MyActivity.this
.getResources()
.getIdentifier(name, "drawable", MyActivity.this.getPackageName());
或
int drawableResourceId = MainActivity.this
.getResources()
.getIdentifier(name, "drawable", MainActivity.this.getPackageName());
Android Studio 告诉我 Activity 不是封闭的 class。这就是为什么我直接想将字符串转换为 R.drawable.name
.
抱歉,我编辑了我的答案,想错了问题:
public static int getDrawable(Context context, String name) {
return context.getResources().getIdentifier(name, "drawable", context.getPackageName());
}
更新*
因为你在适配器中,所以假设你有 MyAdapter 作为 class name do:
public class MyAdapter{
private Context mContext;
public MyAdapter(Context context){
mContext = context;
}
....
那么下面就可以轻松调用了:
getDrawable(mContext, "name")
在我的 android 应用程序中,我需要在 class MyAdapter
中创建一个函数,它在 Activity MyActivity
中使用(这是不是 MainActivity
)。该函数应具有以下结构
public int getDrawableResourceId(String name) {
// naive explanation
return R.drawable. + name
}
例如,如果我调用 getDrawableResorceId("test")
,它应该 return R.drawable.test
的整数值。我无法使用 int drawableResourceId = getResources().getIdentifier(name, "drawable", getPackageName());
,因为 Android Studio 告诉我无法解析方法 getResources()
和 getPackageName()
。如果我用
int drawableResourceId = MyActivity.this
.getResources()
.getIdentifier(name, "drawable", MyActivity.this.getPackageName());
或
int drawableResourceId = MainActivity.this
.getResources()
.getIdentifier(name, "drawable", MainActivity.this.getPackageName());
Android Studio 告诉我 Activity 不是封闭的 class。这就是为什么我直接想将字符串转换为 R.drawable.name
.
抱歉,我编辑了我的答案,想错了问题:
public static int getDrawable(Context context, String name) {
return context.getResources().getIdentifier(name, "drawable", context.getPackageName());
}
更新*
因为你在适配器中,所以假设你有 MyAdapter 作为 class name do:
public class MyAdapter{
private Context mContext;
public MyAdapter(Context context){
mContext = context;
}
....
那么下面就可以轻松调用了:
getDrawable(mContext, "name")