kotlinandroid-widgetandroid-number-picker

The value of NumberPicker doesn't change


I'm a beginner in android and Kotlin. I want to get string values I set as displayedValues from NumberPicker. I tried, but It only returns Int numbers.

After some search, I found a question Formatted value of NumberPicker disappears onClick which might be the solution to my problem.

But I'm beginner and never studied java, so I couldn't apply it to my code. I need your help to figure out whether my code is correct and if it is, I hope to get a solution which can be applied to kotlin Thankyou!

    val pickers = arrayListOf(picker1,picker2,picker3,picker4,picker5,picker6,picker7)
    for (picker in pickers) {
        picker.displayedValues = arrayOf(
            "0", "30", "40", "50", "60", "1시간", "1시간 30분", "2시간", "2시간 30분", "3시간", "3시간 30분", "4시간",
            "4시간 30분", "5시간"
        )
        picker.minValue = 0
        picker.maxValue = 13
        picker.setFormatter { num -> picker.displayedValues[num] }

Solution

  • The translation of the answer there to Kotlin is

    // do this outside the loop because it doesn't depend on picker
    val f = NumberPicker::class.java.getDeclaredField("mInputText")
    f.setAccessible(true)
    
    // inside the loop
    val inputText = f.get(picker) as EditText
    inputText.setFilters(arrayOf())
    

    (it's surrounded by try-catch which you can do in Kotlin as well if you want but the particular catch there is useless; and if you do it should be outside the for loop).