gpt4 book ai didi

java - Android - 如何设置数组中路径的背景图像

转载 作者:行者123 更新时间:2023-12-01 23:54:18 25 4
gpt4 key购买 nike

我有以下数组:

final String[][] dataArr = {
{"R.drawable.bengaltiger", "bengaltiger"},
{"R.drawable.cat", "cat"},
{"R.drawable.chimp", "chimp"},
{"R.drawable.eagle", "eagle"},
{"R.drawable.frog", "frog"},
{"R.drawable.lamb", "lamb"},
{"R.drawable.wolf", "wolf"},
};

从这个开始,我尝试播放声音并使用图像作为按钮的背景:

final Button guessRight = (Button) findViewById(R.id.butRight);
guessRight.setBackgroundResource(R.drawable.bengaltiger);

无法使用 uri 位于数组中的图像设置背景图像,因为函数“setBackgroundResource”需要一个 int 或一个包含字符串的 URI。

我的问题是如何将字符串转换为 URI,以便我可以在“setBackgroundResource”函数中使用数组中的路径?

我的方法正确吗?或者我应该使用另一种方式来存储我的数据或以不同的方式处理它?<​​/p>

谢谢。

最佳答案

这里有很多错误。

  1. 您似乎想使用一个字符串来保存每个 ID 的符号名称。您自己也指出这行不通。
  2. 您将它们存储在二维字符串数组中,这是错误的数据结构。

相反,您需要将它们存储在 Map 中.

Map<Integer, String> imageMap = new HashMap<Integer, String>
// Put the other ones here.
imageMap.put(R.drawable.bengalTiger, "bengaltiger");
.
.
.

// Later on, use them like this:
for(Integer id : imageMap.keyset()) {
String name = imageMap.get(id);
// You can now use "id" and "name" in whatever UI elements you want.
}

此外,如果您在列表中存储任意数量的 ID 和名称,那么为什么要从布局中获取将它们放入的 View 呢?看来您希望以编程方式创建它们,否则为什么不一开始就在 XML 布局中设置所有这些呢?

关于java - Android - 如何设置数组中路径的背景图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15844713/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com