【问题标题】:Set a string value for drawable为drawable设置一个字符串值
【发布时间】:2020-09-25 17:52:12
【问题描述】:

我该如何替换它

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

字符串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();

【问题讨论】:

  • 当前代码有什么问题?我什至不太确定你想在这里做什么?
  • 我想使用变量的值,而不是使用图像资源的直接 id @s_o_m_m_y_e_e
  • 您无法以您想要的方式访问资源文件。您当前的代码是完美的,并且会给出完美的结果。
  • 是的。我知道它工作得很好,我只想知道是否有部分代码可以替换,以便使用字符串值作为源而不是资源 id。

标签: java android string drawable


【解决方案1】:

不可能。您尝试做的事情根本不可能。

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

请查看https://developer.android.com/reference/android/content/res/Resources 以获取更多参考。

【讨论】:

  • 是否可以以不同的方式更改代码,但输出相同,但图像的来源是字符串值?如果可能的话,请参考一些东西。谢谢
  • 类似于替代代码,仅用于字符串的值但具有相同的输出(对话框内的图像)
  • 正如我已经说过的,它不能使用字符串来完成。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-08-16
  • 2022-01-06
  • 2014-02-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多