-1

To make things simple: I got the drawable name from a JSON file and is now in a variable, how can I assign the correct drawable to an ImageView with the name as a String? We can assume that the drawable with that name always exists.

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.
Jordan Cortes
  • 271
  • 1
  • 2
  • 16

2 Answers2

1
imageView.setImageResource(getDrawableFromName(context,"image1.png""));

public static int getDrawableFromName(Context context, String drawableName) {
    return context.getResources().getIdentifier(drawableName, "drawable",
            context.getPackageName());
}
Jagadesh Seeram
  • 2,630
  • 1
  • 16
  • 29
  • thanks buddy! this doesn't break with my logic and is more straightforward than the other answer since I don't need to create additional objects – Jordan Cortes Jan 27 '16 at 15:18
0

Pass the String source and get the 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;
    }
Madhukar Hebbar
  • 3,113
  • 5
  • 41
  • 69