NumberPicker showing wrong value after setValue()

前端 未结 2 757
一向
一向 2021-01-22 21:44

I was trying to create a NumberPicker that would meet my needs, but I stumbled upon something and I don\'t understand what it is.

The behavior is simple, I have three nu

相关标签:
2条回答
  • 2021-01-22 22:20

    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);
    }
    
    0 讨论(0)
  • 2021-01-22 22:42

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

    0 讨论(0)
提交回复
热议问题