【问题标题】:How to avoid randomizing image from array which is in image_view?如何避免从 image_view 中的数组中随机化图像?
【发布时间】:2020-04-16 15:44:27
【问题描述】:

如果我这样做,它有时会设置与 image_view 中相同的图像。比如R.drawable.cat__5_在image_view中,我想从R.drawable.cat__3_,R.drawable.cat__4_,R.drawable.cat__6_,R.drawable.cat__7_,R.drawable.cat__8_.中选择怎么做?

lateinit var random: Random
random = Random()
        var cats = intArrayOf(
                        R.drawable.cat__3_,
                        R.drawable.cat__4_,
                        R.drawable.cat__5_,
                        R.drawable.cat__6_,
                        R.drawable.cat__7_,
                        R.drawable.cat__8_)

            button.setOnClickListener{

            image_view.setImageResource(cats[random.nextInt(cats.size)])
    }

【问题讨论】:

  • 有多种方法可以做到这一点。一种方法是使用 isAlreadySet 和 image 键创建一个 pojo 类,并在设置 image 时将 isAlreadySet 键更新为 true。然后下次可以根据 isAlreadySet 过滤掉,从过滤后的列表中随机选择一个。
  • 随机对象应该只创建一次,而不是每次都创建。因此,我建议将随机变量作为成员并懒惰地创建它。试试这个私有 val random by lazy { new Random() } 并告诉我
  • @vasik988 上述建议有效吗?您需要任何图案来显示图像还是需要随机显示?
  • 感谢 cmets。 @VaikundamRaghul 我将代码更改为我使用的代码。我试图将您的代码 (private val random by lazy { new Random() }) 放在顶层(课外)。但它告诉我“新”是未解决的参考。而且我真的不明白它如何解决我的问题。
  • 糟糕,抱歉 private val random by lazy { Random() } 已经足够了。 new 不需要。因为每次使用默认种子值创建 Random 都会给出相同的值。供您参考,请查看此链接stackoverflow.com/a/5533203/9584758。我希望你的问题应该得到解决。让我知道它是否有效

标签: android r image kotlin random


【解决方案1】:
private var previousIndex = 0  // member variable to track the previous index
private val random by lazy { Random() }
private val cats = intArrayOf(
                        R.drawable.cat__3_,
                        R.drawable.cat__4_,
                        R.drawable.cat__5_,
                        R.drawable.cat__6_,
                        R.drawable.cat__7_,
                        R.drawable.cat__8_)

button.setOnClickListener{       
            image_view.setImageResource(cats[getNewRandomIndex()])
    }


private fun getNewRandomIndex(): Int {
    var newIndex = -1
    while(true) {
        newIndex = random.nextInt(cats.size)
        if(previousIndex != newIndex) {
            previousIndex = newIndex
            break
        }
    }
    return newIndex
}

上述函数getNewRandomIndex() 返回的索引总是与最近的索引不同。所以你每次都会得到不同的图像

【讨论】:

    猜你喜欢
    • 2020-04-14
    • 1970-01-01
    • 1970-01-01
    • 2012-03-10
    • 2013-03-27
    • 1970-01-01
    • 1970-01-01
    • 2013-04-27
    • 2019-04-27
    相关资源
    最近更新 更多