为 drawable 设置一个字符串值

Set a string value for drawable

我该如何替换这个

    Drawable drawable = getResources().getDrawable(R.drawable.imagesample);

用String img的值? (String img 的值为 res drawable 中的图片名称)

我的代码:

     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();

不可能。你想做的事根本不可能。

getDrawable 方法接受一个 int 参数。而你正试图传递 string。您不能调用参数类型错误的方法。

检查 https://developer.android.com/reference/android/content/res/Resources 以供进一步参考。