Android NumberPicker with Formatter doesn't fo

2019-01-11 06:01发布

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 when the NumberPicker is first shown and I initialize it with setValue(0) the 0 does not get formatted (it should display as "-" instead of 0). As soon as I spin the NumberPicker from that point on everything works.

How can I force the NumberPicker to format always - Both on first rendering and also when I enter a number manually with the keyboard?

This is my formatter

public class PickerFormatter implements Formatter {

 private String mSingle;
 private String mMultiple;

 public PickerFormatter(String single, String multiple) {
    mSingle = single;
    mMultiple = multiple;
 }

 @Override
 public String format(int num) {
    if (num == 0) {
        return "-";
    }
    if (num == 1) {
        return num + " " + mSingle;
    }
    return num + " " + mMultiple;
 }

}

I add my formatter to the picker with setFormatter(), this is all I do to the picker.

    picker.setMaxValue(max);
    picker.setMinValue(min);
    picker.setFormatter(new PickerFormatter(single, multiple));
    picker.setWrapSelectorWheel(wrap);

8条回答
SAY GOODBYE
2楼-- · 2019-01-11 07:05

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.

查看更多
Juvenile、少年°
3楼-- · 2019-01-11 07:06

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.

查看更多
登录 后发表回答