how to access the drawable resources by name in android
Note that your approach is almost always the wrong way to do things (better to pass the context into the object itself that is using the drawable than keeping a static Context
somewhere).
Given that, if you want to do dynamic drawable loading, you can use getIdentifier:
Resources resources = context.getResources();
final int resourceId = resources.getIdentifier(name, "drawable",
context.getPackageName());
return resources.getDrawable(resourceId);
Modify image content:
ImageView image = (ImageView)view.findViewById(R.id.imagenElement);
int resourceImage = activity.getResources().getIdentifier(element.getImageName(), "drawable", activity.getPackageName());
image.setImageResource(resourceImage);
You could do something like this.-
public static Drawable getDrawable(String name) {
Context context = YourApplication.getContext();
int resourceId = context.getResources().getIdentifier(name, "drawable", YourApplication.getContext().getPackageName());
return context.getResources().getDrawable(resourceId);
}
In order to access the context from anywhere, you may extend Application class.-
public class YourApplication extends Application {
private static YourApplication instance;
public YourApplication() {
instance = this;
}
public static Context getContext() {
return instance;
}
}
And map it in your Manifest
application
tag
<application
android:name=".YourApplication"
....