如何通过字符串设置imageView的图片?

36

我有一个条目列表和一些位图文件在res/drawable-mdpi目录中。我试图加载与从列表中选择的字符串值相对应的图像,方法是生成路径字符串并使用位图工厂。问题是我认为我的路径不正确,因为即使对于默认图像,位图始终为null。

String name = entries.get(position);
            String img = "res/drawable/logo_" + name.toLowerCase() + ".png"; // create the file name
            icon.setScaleType(ImageView.ScaleType.CENTER_CROP);

            // check to see if the file exists
            File file = new File(img);
            if (file.exists()){

                bm = BitmapFactory.decodeFile(img);
            }
            else{// use the default icon
                bm = BitmapFactory.decodeFile("logo_default.png");
            }

            // set the image and text
            icon.setImageBitmap(bm);

res目录会被复制到设备上吗?我应该使用哪个正确的路径,还是我应该采用不同的方法来处理这个问题?

谢谢


1
你应该了解一下安卓如何处理资源:http://developer.android.com/guide/topics/resources/index.html - WarrenFaith
4个回答

54

如果你的图片在drawable文件夹中,那么你的做法是错误的。

试试这样做:

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

2
getDrawable()已被弃用。 - Srujan Barai
1
尝试使用以下代码获取Drawable对象:Drawable drawable = ContextCompat.getDrawable(getContext(), resID); - Anamaria Miehs

21
不需要使用getDrawable(),直接使用资源ID就可以了。
Resources res = getResources();
String mDrawableName = "myimageName";
int resID = res.getIdentifier(mDrawableName , "drawable", getPackageName());
imgView.setImageResource(resID);`

如何创建 res - parsecer

1
ImageView img = (ImageView) findViewById(R.id.{ImageView id});
img.setImageResource(getResources().getIdentifier("ImageName","drawable",getPackageName()));

0
你可以创建通用函数来获取图像Drawable,如下所示:
public static Drawable getDrawable(Context mContext, String name) {
        int resourceId = mContext.getResources().getIdentifier(name, "drawable", mContext.getPackageName());
        return mContext.getResources().getDrawable(resourceId);
    }

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接