androidkotlinandroid-widgetnumberpickerandroid-number-picker

I'm trying to use the Android NumberPicker widget, but I can't figure out how to set a value from the NumberPicker


I'm a total noob to Kotlin and programming in general, and I want to make an app. In the app involves a NumberPicker widget. I think I got the NP set up properly, as it works when I test it, but I have no clue how to retrieve the user set value from it, and turn it into a variable/value. I think it has to do something with setOnValueChangedListener and OnvalueChangeListener but I can't figure out the syntax, let alone what each part of the syntax does. My question:

What's the syntax for initializing and retrieving values from a NumberPicker and what does each part of the syntax do?


Solution

  • Use OnValueChangedListener

    Java:

       numberPicker.setOnValueChangedListener(new NumberPicker.OnValueChangeListener() {
                    @Override
                    public void onValueChange(NumberPicker picker, int oldVal, int newVal) {
                        String text = "Changed from " + oldVal + " to " + newVal;
                    }
       });
    

    Kotlin:

    numberPicker.setOnValueChangedListener { picker, oldVal, newVal ->
    
                //Display the newly selected number to text view
                text_view.text = "Selected Value : $newVal"
    }