Android NumberPicker OnValueChangeListener

自作多情 提交于 2019-12-01 13:02:38

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(new NumberPicker.OnScrollListener() {

        private int oldValue;  //You need to init this value.

        @Override
        public void onScrollStateChange(NumberPicker numberPicker, int scrollState) {
            if (scrollState == NumberPicker.OnScrollListener.SCROLL_STATE_IDLE) {
                //We get the different between oldValue and the new value
                int valueDiff = 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:

    public class MyNumberPickerScrollListener implements NumberPicker.OnScrollListener {

        private int oldValue;

        public MyNumberPickerScrollListener(int initialValue) {
            oldValue = initialValue;
        }

        @Override
        public void onScrollStateChange(NumberPicker numberPicker, int scrollState) {
            if (scrollState == NumberPicker.OnScrollListener.SCROLL_STATE_IDLE) {
                //We get the different between oldValue and the new value
                int valueDiff = 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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!