【问题标题】:How to randomize image from array but don't repeat previous image after, which is in image_view?如何从数组中随机化图像但不重复之前的图像,它在 image_view 中?
【发布时间】:2020-04-14 08:20:21
【问题描述】:

我想从数组中设置随机图像

var randomElement = array[random.nextInt(array.size)]
                image_view.setImageResource(randomElement)

但之后不要重复

 button.setOnClickListener {
        if (image_view.drawable.constantState != ContextCompat.getDrawable(
                            this,
                            R.drawable.myImage
                        )?.constantState{
        var randomElement = array[random.nextInt(array.size)] //but exclude R.drawable.myImage
    }
}

如何将其从数组中排除,然后添加以避免仅重复上一张图像?

编辑: 尝试使用 sharedPreferences 但按下按钮时应用程序崩溃:

var array = intArrayOf(
        R.drawable.myImage,
        R.drawable.myImage2,
        R.drawable.myImage3)
    button.setOnClickListener {
        var mypref = getSharedPreferences("mypref", Context.MODE_PRIVATE)
         var imagepref = mypref.getInt("image", 0)
                        array.toMutableList().add(imagepref)
                       var image = array[random.nextInt(array.size)]

                        image_view.setImageResource(image)
                        array.drop(image)

                        var editor=mypref.edit()
                        editor.putInt("image", image)
                        editor.apply()
    }

【问题讨论】:

    标签: android arrays kotlin random


    【解决方案1】:

    洗牌一次。 (使用 MutableList https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.collections/shuffle.html 更容易)。

    之后,只需按 0、1、2、3 的顺序取出物品……或者,如果您不再需要它们,您可以使用队列并从前面拉出。

    如果您必须从数组中删除,使用 MutableList 和 remove(index) 会更容易。制作一个新数组并不好玩。

    【讨论】:

    • 我想我问错了。如果我从数组中删除它,我想再次添加它。我的意思是,仅从数组中排除最后一个图像。
    • 你能跟踪最后选择的,虽然相同,但再次运行 random.nextInt
    • 我想我可以使用 sharedPreferences 来跟踪,但是当我按下按钮时我的代码会崩溃。我真的不知道我做得对不对。见已编辑。
    【解决方案2】:

    您可以创建包含最后选择的图像的新变量,并在执行任何操作之前检查 lastImage 是否与新图像不同。在相同的情况下 - 重复过程而不更改 lastImage。

    如果您想在应用程序运行之间保留该值,您可以使用 saveInstanceState 来恢复您的类的实例。

    【讨论】:

    • 感谢您的回答,但主要问题是我不知道如何在从数组中删除元素(图像)后在第二次单击时添加它。在“已编辑:”之后查看我的代码,您可能会明白我要做什么。
    猜你喜欢
    • 2020-04-16
    • 1970-01-01
    • 1970-01-01
    • 2013-09-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-11-12
    • 1970-01-01
    相关资源
    最近更新 更多