【问题标题】:Assign ImageView src with drawable name [duplicate]使用可绘制名称分配 ImageView src [重复]
【发布时间】:2016-01-27 06:19:25
【问题描述】:

为了简单起见:我从 JSON 文件中获取了可绘制对象的名称,并且现在位于变量中,如何将正确的可绘制对象分配给名称为 String 的 ImageView?我们可以假设同名的drawable总是存在的。

String image_name = "image1.png";

ImageView imageView = (ImageView)view.findViewById(R.id.myImageView);
imageView.setImageResource(image_name); // FAIL since is expecting the drawable and not the name as a String.

【问题讨论】:

标签: java android android-drawable


【解决方案1】:
imageView.setImageResource(getDrawableFromName(context,"image1.png""));

public static int getDrawableFromName(Context context, String drawableName) {
    return context.getResources().getIdentifier(drawableName, "drawable",
            context.getPackageName());
}

【讨论】:

  • 谢谢哥们!这不会违反我的逻辑,并且比其他答案更直接,因为我不需要创建其他对象
【解决方案2】:

传递String source 并获取drawable。

private Drawable getImage(String source){
        File imgFile = new File(source);//Absolute path
        Bitmap myBitmap = null;
        Drawable drawable = null;
        if(imgFile.exists()) {
            myBitmap= BitmapFactory.decodeFile(imgFile.getAbsolutePath());
            drawable = new BitmapDrawable(mContext.getResources(),myBitmap);
        }
        return  drawable;
    }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-08-15
    • 2017-11-25
    • 1970-01-01
    • 2020-07-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多