Pranciskus
Pranciskus

Reputation: 539

How to randomize image from array but don't repeat previous image after, which is in image_view?

I want to set random image from array

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

But after that don't repeat it

 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
    }
}

How it can be excluded from array and after that added to avoid repeating only last previous image?

Edited: Trying to use sharedPreferences but app crashes when I press button:

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()
    }

Upvotes: 0

Views: 61

Answers (2)

Kamil Kacprzak
Kamil Kacprzak

Reputation: 156

You can create new variable that will contain last selected image, and before doing any action check if lastImage is different than new image. On case that's the same - repeat process without changing lastImage.

If you want to keep the value between runs of your app, you can use saveInstanceState to restore the instance of your class.

Upvotes: 1

weston
weston

Reputation: 54791

Shuffle the array once. (This is easier with a MutableList https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.collections/shuffle.html).

After that just take the items in order 0,1,2,3... Or if you don't need them anymore you can use a queue and just pull from the front.

If you must remove from array, it's again easier to use a MutableList and remove(index). Making a new array is no fun.

Upvotes: 1

Related Questions