Skip to content Skip to sidebar Skip to footer

Android Numberpicker Onvaluechangelistener

I have a question concerning the Android NumberPicker. When the user is performing a Fling on a NumberPicker, for every single step the Listener for OnValueChange is triggered. Can

Solution 1:

Instead of setOnValueChangedListener you can use setOnScrollListener, and get the value of your picker when the scroll state is SCROLL_STATE_IDLE. Check this example:

    numberPicker.setOnScrollListener(newNumberPicker.OnScrollListener() {

        privateint oldValue;  //You need to init this value.@OverridepublicvoidonScrollStateChange(NumberPicker numberPicker, int scrollState) {
            if (scrollState == NumberPicker.OnScrollListener.SCROLL_STATE_IDLE) {
                //We get the different between oldValue and the new valueintvalueDiff= numberPicker.getValue() - oldValue;

                //Update oldValue to the new value for the next scroll
                oldValue = numberPicker.getValue();

                //Do action with valueDiff
            }
        }
    });

Note that you need to init the value for oldValue variable in the listener. If you need to create a generic listener (that can receive any array of values), you can create a custom class that implements NumberPicker.OnScrollListener and receive the initial value in the constructor. Something like this:

publicclassMyNumberPickerScrollListenerimplementsNumberPicker.OnScrollListener {

        privateint oldValue;

        publicMyNumberPickerScrollListener(int initialValue) {
            oldValue = initialValue;
        }

        @OverridepublicvoidonScrollStateChange(NumberPicker numberPicker, int scrollState) {
            if (scrollState == NumberPicker.OnScrollListener.SCROLL_STATE_IDLE) {
                //We get the different between oldValue and the new valueintvalueDiff= numberPicker.getValue() - oldValue;

                //Update oldValue to the new value for the next scroll
                oldValue = numberPicker.getValue();

                //Do action with valueDiff
            }
        }
    }

Read the NumberPicker.onScrollListener documentation for more information.

Post a Comment for "Android Numberpicker Onvaluechangelistener"