为可绘制设置字符串值

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

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.

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:

确定