Android的NumberPicker与格式化不会在第一次呈现

Android的NumberPicker与格式化不会在第一次呈现

本文介绍了Android的NumberPicker与格式化不会在第一次呈现格式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有很多选择器,有一个格式化的,只要我纺numberpicker或放一个值自己格式的数字。这工作得很好,但是当numberpicker首先显示的是,我初始化它的setValue(0)0不会被格式化(它应该显示为 - ,而不是0)。当我旋转数选择器,从这一点上一切正常。

I have a number picker that has a formatter that formats the numbers as soon as I spin the numberpicker or put a value in myself. 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 number picker, from that point on everything works.

我怎么能强迫numberpicker第一次渲染瞬间格式化(以及当我输入一个号码与键盘)?

How can I force the numberpicker to format instantly on first rendering (and also when I enter a number with the keyboard)?

感谢所有的建议!

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;
}

}

这是我的格式,我只是把它添加到选择器的picker.setFormatter方法​​,像这样:

this is my formatter and i just add it to the picker with the picker.setFormatter method, like so:

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

这是我做的选择器。

推荐答案

我也遇到了这个恼人的小的。使用从这个答案的技术拿出一个讨厌的,但有效的修复。

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();
}

调用私有 changeValueByOne 方法实例化我的电话号码拾取后马上好像踢了足够的表现应该如何格式化。该数字选择器出现非常干净与格式正确的第一个值。就像我说的,讨厌的,但有效的。

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.

这篇关于Android的NumberPicker与格式化不会在第一次呈现格式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-18 08:56