英文:
Set a string value for drawable
问题
String img = "sampleimage";
// 图片弹出对话框的代码
LayoutInflater inflater = LayoutInflater.from(MainActivity.this);
View subView = inflater.inflate(R.layout.dialog, null);
final ImageView subImageView = (ImageView) subView.findViewById(R.id.image);
int drawableResourceId = getResources().getIdentifier(img, "drawable", getPackageName());
Drawable drawable = getResources().getDrawable(drawableResourceId);
subImageView.setImageDrawable(drawable);
// 弹出对话框的代码
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("恭喜");
builder.setMessage("感谢您的帮助!");
builder.setView(subView);
builder.setPositiveButton("确定", null);
builder.show();
英文:
How can I replace this
Drawable drawable = getResources().getDrawable(R.drawable.imagesample);
with the value of String img? (value of String img is the name of the image in res drawable)
My Code:
String img = "sampleimage";
// code for image in pop-up dialog
LayoutInflater inflater = LayoutInflater.from(MainActivity.this);
View subView = inflater.inflate(R.layout.dialog, null);
final ImageView subImageView = (ImageView) subView.findViewById(R.id.image);
Drawable drawable = getResources().getDrawable(R.drawable.imagesample);
subImageView.setImageDrawable(drawable);
// code for a pop-up dialog
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Congratulations");
builder.setMessage("Thanks for helping me!");
builder.setView(subView);
builder.setPositiveButton("Ok", null);
builder.show();
答案1
得分: 0
不可能的。你正在尝试做的事情根本不可能。
getDrawable
方法接受一个 int
参数。而你正试图传递一个 string
。你不能用错误类型的参数调用一个方法。
请参考 https://developer.android.com/reference/android/content/res/Resources 获取更多参考资料。
英文:
Not Possible. What you are trying to do is simply not possible.
The getDrawable
method accepts an int
argument. And you are trying to pass a string
. You can not call a method with wrong type of argument.
Check https://developer.android.com/reference/android/content/res/Resources for further reference.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论