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
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.
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.
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.
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)
int resId = getResources().getIdentifier("your_drawable_name","drawable",YourActivity.this.getPackageName());
Drawable d = YourActivity.this.getResources().getDrawable(resId);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With