【问题标题】:Iterate through ImageViews and set random drawable and visibility遍历 ImageViews 并设置随机可绘制和可见性
【发布时间】:2019-05-03 10:46:14
【问题描述】:

我做了一个小游戏,但在迭代 ImageView 时遇到了问题。

我有 12 个 ImageView,应该随机显示没有苹果、绿色或红色苹果。

如何遍历 ImageViews 并设置 Visibility 和 drawable? 应用崩溃:“应用已停止”

    void shuffleApples() {

    ImageView[] apples = new ImageView[12];
    apples[0] = img_apple1;
    apples[1] = img_apple2;
    apples[2] = img_apple3;
    apples[3] = img_apple4;
    apples[4] = img_apple5;
    apples[5] = img_apple6;
    apples[6] = img_apple7;
    apples[7] = img_apple8;
    apples[8] = img_apple9;
    apples[9] = img_apple10;
    apples[10] = img_apple11;
    apples[11] = img_apple12;

    for(int i = 0; i < apples.length; i++) {
        Random randomAppleVisibility = new Random();
        Random randomAppleColor = new Random();
        int appleVisibility = randomAppleVisibility.nextInt(0);
        int appleColor = randomAppleColor.nextInt(0);

        if(appleVisibility==0) {
            apples[i].setVisibility(View.GONE);
        }
        else {
            if(appleColor==0) {
                apples[i].setImageResource(R.drawable.apple_red);
                redApples++;
            }
            else {
                apples[i].setImageResource(R.drawable.apple_green);
                greenApples++;
            }
        }
    }
}

感谢您的帮助!

【问题讨论】:

    标签: android random imageview visibility


    【解决方案1】:

    如果您想生成01 的随机整数值,请执行以下操作:

    int appleVisibility = randomAppleVisibility.nextInt(2);
    int appleColor = randomAppleColor.nextInt(2);
    

    这个

    nextInt(0) 
    

    抛出一个java.lang.IllegalArgumentException,因为参数必须是一个正数。
    关于nextInt()

    返回一个伪随机的、在 0 之间均匀分布的 int 值 (含)和指定值(不含)

    你应该考虑把这些行:

    Random randomAppleVisibility = new Random();
    Random randomAppleColor = new Random();
    

    for 循环之前。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-10-14
      • 1970-01-01
      • 2014-01-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-09-02
      • 2015-11-01
      相关资源
      最近更新 更多