为 ImageView src 分配可绘制名称
Assign ImageView src with drawable name
为简单起见:我从 JSON 文件中获得了可绘制对象的名称,现在它位于一个变量中,我如何才能将正确的可绘制对象分配给名称为 ImageView
的 String
?我们可以假设具有该名称的可绘制对象始终存在。
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.
imageView.setImageResource(getDrawableFromName(context,"image1.png""));
public static int getDrawableFromName(Context context, String drawableName) {
return context.getResources().getIdentifier(drawableName, "drawable",
context.getPackageName());
}
通过 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;
}
为简单起见:我从 JSON 文件中获得了可绘制对象的名称,现在它位于一个变量中,我如何才能将正确的可绘制对象分配给名称为 ImageView
的 String
?我们可以假设具有该名称的可绘制对象始终存在。
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.
imageView.setImageResource(getDrawableFromName(context,"image1.png""));
public static int getDrawableFromName(Context context, String drawableName) {
return context.getResources().getIdentifier(drawableName, "drawable",
context.getPackageName());
}
通过 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;
}