How to convert String to Drawable

I have many icons in the folder with the ability to transfer and I have the name String. How can I access a folder with a choice and change the background image (or any view) using this name dynamically. thanks

+4
source share
6 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 to set drawable anyway:

view.setBackground(drawable)
+21
source
int resId = getResources().getIdentifier("your_drawable_name","drawable",YourActivity.this.getPackageName());
Drawable d = YourActivity.this.getResources().getDrawable(resId);
+8
source

:

ImageView imageView = new ImageView(this);
imageView.setBackground(getResources().getDrawable(getResources().getIdentifier("name","id",getPackageName())));
+5

:

public Bitmap getPic (int number)
{
    return
        BitmapFactory.decodeResource
        (
            getResources(), getResourceID("myImage_" + number, "drawable", getApplicationContext())
        );
}

protected final static int getResourceID
(final String resName, final String resType, final Context ctx)
{
    final int ResourceID =
        ctx.getResources().getIdentifier(resName, resType,
            ctx.getApplicationInfo().packageName);
    if (ResourceID == 0)
    {
        throw new IllegalArgumentException
        (
            "No resource string found with name " + resName
        );
    }
    else
    {
        return ResourceID;
    }
}
+3

, :

int id = getResources().getIdentifier("name_of_resource", "id", getPackageName());

, (, ):

Drawable drawable = getResources().getDrawable(id);
+1

, - , @FD_ examples

:

- , context, "getResources()" "getPackageName()", "getDrawable (id)" , getDrawer (int id, Theme theme). ( ):

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

Source: https://habr.com/ru/post/1527528/


All Articles