Home » Android » Android NumberPicker widget, how to get value entered via softkeyboard?

Android NumberPicker widget, how to get value entered via softkeyboard?

Posted by: admin June 15, 2020 Leave a comment


I’m having trouble getting the edit field of my NumberPicker to work properly, I’ve read several helpful answers to similar questions but none of them seem to address this particular issue. Although the increment and decrement buttons do work correctly, if I enter a number using the soft keyboard I am unable to retrieve that value using the NumberPicker.getValue() method. I’ve tried using my own NumberPicker.OnValueChangedListener() but it doesn’t get called unless I click the up or down buttons, not when I press the soft keyboard Done button as some have suggested. Can anybody help me with this? Is this an Android bug?

Here is my XML layout:

android:layout_width="wrap_content" android:layout_height="wrap_content">
    <TextView android:id="@+id/textView1" android:layout_weight="1"
        android:layout_height="wrap_content" android:text="@string/enter_nights_"
        android:layout_width="0dp" android:padding="10dip"
        android:layout_height="wrap_content" />

and my initialization code from my Activity onCreate():

    mNumNights = (NumberPicker) findViewById(R.id.numPick);
    mNumNights.setOnValueChangedListener(new NumberPicker.OnValueChangeListener() {
        public void onValueChange(NumberPicker picker, int oldVal, int newVal) {
            // do something here
            Log.d(TAG, "Number of Nights change value.");

And on exit from the Activity I get the value like so:

            mNights = mNumNights.getValue();

I don’t see any other methods in Android NumberPicker documentation. I did see a post suggesting hooking onEditorActionListener() to get the Done button, however this doesn’t tell me how to get the value! So, to sum up, my question is how do I get the value and why isn’t the NumberPicker updating its value automatically?


EDIT: I stumbled across this SO question which is very similar to my question, the answers there look helpful although I’m hoping there is a better approach than suggested there.

How to&Answers:

To have the activity pick up the edit, you need to call nNumNights.clearFocus(); before calling nNumNights.getValue();. The call will update the control’s value.