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

Alan Moore picture Alan Moore · Oct 17, 2013 · Viewed 6.9k times · Source

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:

<LinearLayout 
android:orientation="horizontal" 
android:layout_width="wrap_content" android:layout_height="wrap_content">
    <TextView android:id="@+id/textView1" android:layout_weight="1"
        android:textAppearance="?android:attr/textAppearanceLarge"
        android:layout_height="wrap_content" android:text="@string/enter_nights_"
        android:layout_width="0dp" android:padding="10dip"
        android:textColor="@color/black"
        ></TextView>
    <NumberPicker
        android:id="@+id/numPick"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />
</LinearLayout>

and my initialization code from my Activity onCreate():

    mNumNights = (NumberPicker) findViewById(R.id.numPick);
    mNumNights.setMinValue(1);
    mNumNights.setMaxValue(99);
    mNumNights.setValue(mNights);
    mNumNights.setOnValueChangedListener(new NumberPicker.OnValueChangeListener() {
        @Override
        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?

Thanks!

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.

Answer

hfann picture hfann · Mar 3, 2014

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.