我的问题是我创建了图像数组,并且总是随机让屏幕显示这些图像中的 2 个,并且在按下 next_button 和 next 显示 2 个图像之后,但是当我转动屏幕时它会全部重置。我知道活动会改变,它必须保存“onsaveinstancestate”,但我不知道有人可以给我一个解决方案。附言。抱歉,我的代码看起来很糟糕,因为我从 kotlin 和 OOP 开始。
import android.os.Bundle
import android.view.View
import android.widget.ImageView
import androidx.appcompat.app.AppCompatActivity
import kotlinx.android.synthetic.main.activity_roll.*
import kotlinx.android.synthetic.main.activity_roll0.*
import java.lang.NullPointerException
import kotlin.random.Random
class RollActivity0 : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_roll0)
//init array
var cards = arrayOf(R.drawable.bart_cassidy,
R.drawable.black_jack,
R.drawable.calamity_janet,
R.drawable.el_gringo,
R.drawable.jesse_jones,
R.drawable.jourdonnais,
R.drawable.kit_carlson,
R.drawable.lucky_duke,
R.drawable.paul_regret,
R.drawable.pedro_ramirez,
R.drawable.rose_doolan,
R.drawable.sid_ketchum,
R.drawable.slab_the_killer,
R.drawable.suzy_lafayette,
R.drawable.vulture_sam,
R.drawable.willy_the_kid)
val random_index = java.util.Random()
var index = 0
//shuffling array
for (i in cards.size - 1 downTo 1)
{
val j = random_index.nextInt(i + 1)
val tmp = cards[i]
cards[i] = cards[j]
cards[j] = tmp
}
imageView3.setImageResource(cards[index])
index++ //next image
imageView4.setImageResource(cards[index])
index++ //next image
next_button1.setOnClickListener {
if ( index >= cards.size )//if i am on end array make new shuffled array
{
//shuffling array
for (i in cards.size - 1 downTo 1)
{
val j = random_index.nextInt(i + 1)
val tmp = cards[i]
cards[i] = cards[j]
cards[j] = tmp
}
index = 0 //new start
}
imageView3.setImageResource(cards[index])
index++
imageView4.setImageResource(cards[index])
index++
}
}
}