How to set an imageView's image from a string?

僤鯓⒐⒋嵵緔 提交于 2019-11-27 19:19:59

if you have the image in the drawable folder you are going about this the wrong way.

try something like this

Resources res = getResources();
String mDrawableName = "logo_default";
int resID = res.getIdentifier(mDrawableName , "drawable", getPackageName());
Drawable drawable = res.getDrawable(resID );
icon.setImageDrawable(drawable );

No need to use getDrawable() you directly use the resource id like

String mDrawableName = "myimageName"; int resID = res.getIdentifier(mDrawableName , "drawable", getPackageName()); imgView.setImageResource(resID);

You can Create Common Function for getting image drawable like this:

public static Drawable getDrawable(Context mContext, String name) {
        int resourceId = mContext.getResources().getIdentifier(name, "drawable", mContext.getPackageName());
        return mContext.getResources().getDrawable(resourceId);
    }
ImageView img = (ImageView) findViewById(R.id.{ImageView id});
img.setImageResource(getResources().getIdentifier("ImageName","drawable",getPackageName()));
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!