NumberPicker showing wrong value after setValue()

醉酒当歌 提交于 2019-12-02 02:39:58

I had a similar issue. I was using the scrollBy() method to set the value of the number picker programmatically and on two of the values, wrong numbers were shown. After some investigation I realized that there was some code in the onTouch of the NumberPicker, which was not being called when setting values programmatically.

So I simulate a touch right after I set a value.

public void changeValueByOne(final boolean increment) {

    int scrollStep = getHeight() / 3;

    scrollBy(0, increment ? scrollStep : (-1 * scrollStep));

    simulateTouchHack();
}

private void simulateTouchHack() {
    MotionEvent motionEventDown = MotionEvent.obtain(
            SystemClock.uptimeMillis(),
            SystemClock.uptimeMillis() + 100,
            MotionEvent.ACTION_DOWN,
            getWidth() / 2,
            getHeight() / 2,
            0
    );

    dispatchTouchEvent(motionEventDown);

    MotionEvent motionEventUp = MotionEvent.obtain(
            SystemClock.uptimeMillis() + 200,
            SystemClock.uptimeMillis() + 300,
            MotionEvent.ACTION_UP,
            getWidth() / 2,
            getHeight() / 2,
            0
    );

    dispatchTouchEvent(motionEventUp);
}

Calling invalidate() on the NumberPicker might help. I called it from Fragment.onViewCreated and so far so good

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