【问题标题】:How to change an ImageView with a filename如何使用文件名更改 ImageView
【发布时间】:2018-03-10 15:12:58
【问题描述】:

我有一个字符串,其中包含我想要 (R.drawable.square) 放入 imageview 的文件的名称。

String shape = "square"

我正在尝试使用下面的方法来显示图像

imageView.setImageResource()

在作品中硬编码文件名,但我希望能够传入不同的文件名。

image.setImageResource(R.drawable.square)

tl;博士 无法从 String:"square" 到 int:R.drawable.square

【问题讨论】:

标签: android imageview


【解决方案1】:

请看Android, reference things in R.drawable. using variables?

//to retrieve image in res/drawable and set image in ImageView
String imageName = "picture"
int resID = getResources().getIdentifier(imageName, "drawable", "package.name");
ImageView image;
image.setImageResource(resID );

【讨论】:

  • 引用链接不考虑答案。
【解决方案2】:

我是把图片放到assets目录下实现的效果

【讨论】:

    【解决方案3】:

    我认为最好在 Map 对象中使用字符串作为键,将资源 ID 作为值。

        Map<String, Integer> resources = new HashMap<>();
    
        resources.put("square", R.drawable.square);
        // resources.put("...", R.drawable....);
    
        imageView.setImageResource(resources.get("square"));
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-06-01
      • 2011-08-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多