kotlin 如何根据另一个数字选取器的值更改其值

gab6jxml  于 2023-02-24  发布在  Kotlin
关注(0)|答案(1)|浏览(106)

如果第一个数字选取器的值是“B”或“E”,我希望在数字选取器中显示一组不同的值
我尝试创建if语句,但在选择“E”或“B”时崩溃

val chordPicker = findViewById<NumberPicker>(R.id.number_picker)
        val chordImage = findViewById<ImageView>(R.id.chordImage)

        val chordValues = arrayOf("C", "D", "E", "F", "G", "A", "B")
        var chordValue = chordValues[0]

        chordPicker.displayedValues = chordValues
        chordPicker.minValue = 0
        chordPicker.maxValue = chordValues.size - 1

        val chordTypePicker = findViewById<NumberPicker>(R.id.number_picker2)
        chordTypePicker.displayedValues = chordTypeValues
        chordTypePicker.minValue = 0
        chordTypePicker.maxValue = chordValues.size - 1

        chordPicker.setOnValueChangedListener { picker, oldVal, newVal ->
            chordValue = chordValues[newVal]
            val newList: Array<String> = if (chordValue == "E" || chordValue == "B") {
                arrayOf("M", "m", "7", "m7", "dim", "maj7", "m6", "aug")
            } else {
                arrayOf("M", "m", "7", "m7", "dim", "maj7", "m6", "aug", "#", "#7")
            }
            chordTypeValues = newList
            chordTypePicker.minValue = 0
            chordTypePicker.maxValue = newList.size - 1
            chordTypePicker.displayedValues = newList
        }
bfhwhh0e

bfhwhh0e1#

您应该更新侦听器中chordTypePicker的值。
代码可能如下所示:

val numberPicker1: NumberPicker = findViewById(R.id.number_picker)
    val chordList = arrayOf("C", "D", "E", "F", "G", "A", "B", "C")
    numberPicker1.displayedValues = chordList
    numberPicker1.minValue = 0
    numberPicker1.maxValue = chordList.size - 1

    val numberPicker2: NumberPicker = findViewById(R.id.number_picker2)

    numberPicker1.setOnValueChangedListener { picker, oldVal, newVal ->
        val newList: Array<String> = if (chordList[newVal] == "E" || chordList[newVal] == "B") {
            arrayOf("M", "m", "7", "m7", "dim", "maj7", "m6", "aug")
        } else {
            arrayOf("M", "m", "7", "m7", "dim", "maj7", "m6", "aug", "#", "#7")
        }
        numberPicker2.minValue = 0
        numberPicker2.maxValue = newList.size - 1
        numberPicker2.displayedValues = newList
    }

注意:在设置第二个数字选择器的值之前,您需要更新maxValue和minValue(这是可选的,因为在这两种情况下,值都是0)。

相关问题