Android NumberPicker with Formatter doesn't format on first rendering

前端 未结 9 1826

I have a NumberPicker that has a formatter that formats the displayed numbers either when the NumberPicker spins or when a value is entered manually. This works fine, but wh

相关标签:
9条回答
  • 2020-12-01 09:44

    The answer provided by NoActivity worked for me but I only had to do:

    View firstItem = bugFixNumberPicker.getChildAt(0);
    if (firstItem != null) {
      firstItem.setVisibility(View.INVISIBLE);
    }
    

    to fix the issue. I did not need to subclass NumberPicker. I did not see the issue where picker elements disappear on touch.

    0 讨论(0)
  • 2020-12-01 09:51

    Calling the private method changeValueByOne() via reflection as described in an earlier answer works for me on API Level 16 (Android 4.1.2 and up), but it does not seem to help on API Level 15 (Android 4.0.3), however!

    What works for me on API Level 15 (and up) is to use your own custom formatter to create String array and pass that with the method setDisplayedValues() to the number picker.

    See also: Android 3.x and 4.x NumberPicker Example

    0 讨论(0)
  • 2020-12-01 09:55

    I also encountered this annoying little bug. Used a technique from this answer to come up with a nasty but effective fix.

    NumberPicker picker = (NumberPicker)view.findViewById(id.picker);
    picker.setMinValue(1);
    picker.setMaxValue(5);
    picker.setWrapSelectorWheel(false);
    picker.setFormatter(new NumberPicker.Formatter() {
        @Override
        public String format(int value) {
            return my_formatter(value);
        }
    });
    
    try {
        Method method = picker.getClass().getDeclaredMethod("changeValueByOne", boolean.class);
        method.setAccessible(true);
        method.invoke(picker, true);
    } catch (NoSuchMethodException e) {
        e.printStackTrace();
    } catch (IllegalArgumentException e) {
        e.printStackTrace();
    } catch (IllegalAccessException e) {
        e.printStackTrace();
    } catch (InvocationTargetException e) {
        e.printStackTrace();
    }
    

    Calling that private changeValueByOne method immediately after instantiating my number picker seems to kick the formatter enough to behave how it should. The number picker comes up nice and clean with the first value formatted correctly. Like I said, nasty but effective.

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