【问题标题】:Loop for resources循环获取资源
【发布时间】:2021-10-15 13:28:10
【问题描述】:

我正在为我的问题寻找解决方案,即自动连接 ImageView 和资源中的正确 JPG。 我有一个简单的数组,上面有神的名字,比如:

final String[] godslist = {"Achilles", "Agni", "Ah Muzen Cab", "Ah Puch", "Amaterasu", "Anhur", "Anubis", "Ao Kuang", "Aphrodite", "Apollo", "Arachne", "Ares", "Artemis", "Artio"}

final ImageView godImage = findViewById(R.id.godImage);
final TextView godName = findViewById(R.id.nameOfGod);

int randomGod = (int) (Math.random() * 14);
godName.setText(godslist[randomGod]);

目前,它运行良好。在 TextView 中,我从数组中随机获得一个神的名字。 问题在于将选择的上帝与他的形象联系起来。我想到了一个循环,该循环将按所选上帝的名称搜索资源,例如“阿喀琉斯”。在资源中,我有一个名为“achilles.jpg”等的文件,所以它应该是 godName.setImageResource(R.drawable.achilles);。不是每个神的名字都只由一个词组成——比如“Ah Muzen Cab”和drawable不能用空格命名(但现在这不是一个大问题)。由于某些原因,drawable 也不能以大写字符开头,所以我可能需要这样做:

godName.setText(godName.getText().toString().toLowerCase());

然后我应该使用一些循环在资源中查找名称。如果可以这样工作,下面的代码应该是最简单的,但是...

godImage.setImageResource(R.drawable.(godName.setText(godName.getText().toString().toLowerCase())));

同样的问题是来自资源的声音(取决于随机选择的神),但当我弄清楚如何设置图像时会更容易。感谢您的帮助。

【问题讨论】:

    标签: java android arrays loops resources


    【解决方案1】:

    您可以将数据封装在单独的类中,并在随机选择数组索引时使用其实例:

    public class GodData {
            public final String name;
            public final String imageResId;
            public final String soundResId;
    
            public GodData(String name, String imageResId, String soundResId) {
                this.name = name;
                this.imageResId = imageResId;
                this.soundResId = soundResId;
            }
        }
    
    final GodData[] godslist = {new GodData("Achilles", R.drawable.achilles, R.raw.achilles_sound), ...}
    
    GodData randomGod = godslist((int) (Math.random() * 14));
    godName.setText(randomGod.name);
    godImage.setImageResource(randomGod. imageResId);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-12-08
      • 1970-01-01
      • 2021-12-27
      • 2012-10-05
      • 2010-12-17
      • 2021-11-25
      • 1970-01-01
      • 2020-01-21
      相关资源
      最近更新 更多