Issue
Inside my android application, I need to create a function inside a class MyAdapter
which is used inside the Activity MyActivity
(which is not the MainActivity
). The function should have the following structure
public int getDrawableResourceId(String name) {
// naive explanation
return R.drawable. + name
}
For example if I call getDrawableResorceId("test")
it should return the integer value of R.drawable.test
. I cannot work with int drawableResourceId = getResources().getIdentifier(name, "drawable", getPackageName());
because Android Studio tells me that cannot resolve the methods getResources()
and getPackageName()
. If I replace it with
int drawableResourceId = MyActivity.this
.getResources()
.getIdentifier(name, "drawable", MyActivity.this.getPackageName());
or
int drawableResourceId = MainActivity.this
.getResources()
.getIdentifier(name, "drawable", MainActivity.this.getPackageName());
Android Studio tells me that the Activity is not an enclosing class. That is why I directly want to cast the String into R.drawable.name
.
Solution
Sorry I edited my answer, got the wrong question in mind:
public static int getDrawable(Context context, String name) {
return context.getResources().getIdentifier(name, "drawable", context.getPackageName());
}
Update *
Since you are in an Adapter let's say you have MyAdapter as class name do:
public class MyAdapter{
private Context mContext;
public MyAdapter(Context context){
mContext = context;
}
....
Then below you can easily call:
getDrawable(mContext, "name")
Answered By - Mike
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.