How can I convert String to Drawable

孤街醉人 提交于 2019-11-27 01:59:18

问题


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


回答1:


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)



回答2:


int resId = getResources().getIdentifier("your_drawable_name","drawable",YourActivity.this.getPackageName());
Drawable d = YourActivity.this.getResources().getDrawable(resId);



回答3:


It can be done like this:

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



回答4:


Try this:

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;
    }
}



回答5:


if you have the filename as string you can use:

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

with this id you can access it like always (assumed its a drawable):

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



回答6:


use case if not in any activity, using @FD_ examples

Note:

if you are not in any activity you have to send context param in order to use "getResources()" or "getPackageName()", and "getDrawable(id)" is deprecated, use getDrawer(int id, Theme theme) instead. (Theme can be null):

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


来源:https://stackoverflow.com/questions/21856260/how-can-i-convert-string-to-drawable

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!