You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Android Studio中Previous按钮首次点击崩溃问题求助

题库Previous按钮首次点击崩溃问题解决方案

问题描述

运行应用时,只有先点击Next按钮后,Previous按钮才能正常工作;若首次直接点击Previous按钮会导致崩溃。需要修改代码让首次点击Previous按钮时直接跳转到题库的最后一题。

用户提供的代码:

private val questionBank = listOf(
    Question(R.string.question_australia, true),
    Question(R.string.question_oceans, true),
    Question(R.string.question_mideast, false),
    Question(R.string.question_africa, false),
    Question(R.string.question_americas, true),
    Question(R.string.question_asia, true))

private var currentIndex = 0

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    //setContentView(R.layout.activity_main)
    binding = ActivityMainBinding.inflate(layoutInflater)
    setContentView(binding.root)


    binding.trueButton.setOnClickListener { checkAnswer(true) }

    binding.falseButton.setOnClickListener { checkAnswer(false)}

    binding.prevButton.setOnClickListener {
        currentIndex = (currentIndex - 1) % questionBank.size
        updateQuestion()
    }

    binding.nextButton.setOnClickListener {
        currentIndex = (currentIndex + 1) % questionBank.size
        updateQuestion()
    }

    updateQuestion()

}

问题原因

问题出在负数取模的行为上。Kotlin中,负数取模的结果仍为负数:当currentIndex初始值为0时,0 - 1 = -1,执行-1 % questionBank.size(此处题库长度为6)会得到-1。用这个负数索引访问questionBank时,会触发数组越界异常,导致应用崩溃。

修改方案

方案一:调整取模运算逻辑

修改Previous按钮的点击事件代码,通过先加上题库长度确保计算值为正数,再取模:

binding.prevButton.setOnClickListener {
    currentIndex = (currentIndex - 1 + questionBank.size) % questionBank.size
    updateQuestion()
}
  • 当currentIndex为0时,0 -1 +6 =5,取模后得到5,对应题库最后一题
  • 后续点击时,索引会正常循环,不会出现负数

方案二:直观判断索引值

如果觉得取模逻辑不好理解,也可以用条件判断的方式实现:

binding.prevButton.setOnClickListener {
    currentIndex = if (currentIndex == 0) questionBank.size - 1 else currentIndex - 1
    updateQuestion()
}
  • 直接判断当前是否为第一题(索引0),若是则跳转到最后一题(索引questionBank.size-1),否则索引减一,逻辑清晰易懂

内容的提问来源于stack exchange,提问作者Devarsh Patel

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.24 18:37:15