为可绘制设置字符串值

huangapple go评论91阅读模式
英文:

Set a string value for drawable

问题

  1. String img = "sampleimage";
  2. // 图片弹出对话框的代码
  3. LayoutInflater inflater = LayoutInflater.from(MainActivity.this);
  4. View subView = inflater.inflate(R.layout.dialog, null);
  5. final ImageView subImageView = (ImageView) subView.findViewById(R.id.image);
  6. int drawableResourceId = getResources().getIdentifier(img, "drawable", getPackageName());
  7. Drawable drawable = getResources().getDrawable(drawableResourceId);
  8. subImageView.setImageDrawable(drawable);
  9. // 弹出对话框的代码
  10. AlertDialog.Builder builder = new AlertDialog.Builder(this);
  11. builder.setTitle("恭喜");
  12. builder.setMessage("感谢您的帮助!");
  13. builder.setView(subView);
  14. builder.setPositiveButton("确定", null);
  15. builder.show();
英文:

How can I replace this

  1. 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:

  1. String img = "sampleimage";
  2. // code for image in pop-up dialog
  3. LayoutInflater inflater = LayoutInflater.from(MainActivity.this);
  4. View subView = inflater.inflate(R.layout.dialog, null);
  5. final ImageView subImageView = (ImageView) subView.findViewById(R.id.image);
  6. Drawable drawable = getResources().getDrawable(R.drawable.imagesample);
  7. subImageView.setImageDrawable(drawable);
  8. // code for a pop-up dialog
  9. AlertDialog.Builder builder = new AlertDialog.Builder(this);
  10. builder.setTitle("Congratulations");
  11. builder.setMessage("Thanks for helping me!");
  12. builder.setView(subView);
  13. builder.setPositiveButton("Ok", null);
  14. 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.

huangapple
  • 本文由 发表于 2020年9月26日 01:52:12
  • 转载请务必保留本文链接:https://go.coder-hub.com/64069119.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定