Android Cast String name to R.drawable.name

MachineLearner :

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.

Mike :

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")

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=403560&siteId=1