Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I convert String to Drawable

I have many icon in drawable folder and I have their name as String. How can I access to drawable folder and change background imageView (or any view) use these name in dynamically. Thanks

like image 991
Utku Soytaş Avatar asked Feb 18 '14 14:02

Utku Soytaş


People also ask

How do you add Drawables?

Drag and drop your images directly onto the Resource Manager window in Android Studio. Alternatively, you can click the plus icon (+), choose Import Drawables, as shown in figure 3, and then select the files and folders that you want to import. Figure 3: Select Import Drawables from the dropdown menu.

What is drawable and drawable v24?

Choose between drawable and drawable-v24. Classic drawable resources such as images are stored in the drawable folder. In contrast, vector drawables are stored in drawable-v24 . For this project, keep the drawable default and click OK.

What are Drawables in Android?

A drawable resource is a general concept for a graphic that can be drawn to the screen and which you can retrieve with APIs such as getDrawable(int) or apply to another XML resource with attributes such as android:drawable and android:icon . There are several different types of drawables: Bitmap File.


2 Answers

This can be done using reflection:

String name = "your_drawable";
final Field field = R.drawable.getField(name);
int id = field.getInt(null);
Drawable drawable = getResources().getDrawable(id);

Or using Resources.getIdentifier():

String name = "your_drawable";
int id = getResources().getIdentifier(name, "drawable", getPackageName());
Drawable drawable = getResources().getDrawable(id);

Then use this for setting the drawable in either case:

view.setBackground(drawable)
like image 155
FD_ Avatar answered Sep 23 '22 21:09

FD_


int resId = getResources().getIdentifier("your_drawable_name","drawable",YourActivity.this.getPackageName());
Drawable d = YourActivity.this.getResources().getDrawable(resId);
like image 26
M. Bongini Avatar answered Sep 24 '22 21:09

M. Bongini