将Android NumberPicker限制为数字键盘以进行数字输入(不是Alpha键盘)

Cri*_*onX 5 android android-softkeyboard numberpicker

有没有办法在选择NumberPicker时建议或限制键盘输入,因此在输入值时只显示数字控件,类似于如何使用android:inputType="number"EditText?

我有一系列值,从0.0到100.0,增量为0.1,我希望能够在Android 4.3中使用NumberPicker进行选择.为了使数字可选,我创建了一个与这些值对应的字符串数组,如下所示:

    NumberPicker np = (NumberPicker) rootView.findViewById(R.id.programmingNumberPicker);        
    int numberOfIntensityOptions = 1001;

    BigDecimal[] intensityDecimals = new BigDecimal[numberOfIntensityOptions];
    for(int i = 0; i < intensityDecimals.length; i++ )
    {
        // Gets exact representations of 0.1, 0.2, 0.3 ... 99.9, 100.0
        intensityDecimals[i]  = BigDecimal.valueOf(i).divide(BigDecimal.TEN);
    }

    intensityStrings = new String[numberOfIntensityOptions];
    for(int i = 0; i < intensityDecimals.length; i ++)
    {
        intensityStrings[i] = intensityDecimals[i].toString();
    }

    // this will allow a user to select numbers, and bring up a full keyboard. Alphabetic keys are
    // ignored - Can I somehow change the keyboard for this control to suggest to use *only* a number keyboard
    // to make it much more intuitive? 
    np.setMinValue(0);
    np.setMaxValue(intensityStrings.length-1);
    np.setDisplayedValues(intensityStrings);
    np.setWrapSelectorWheel(false);
Run Code Online (Sandbox Code Playgroud)

作为更多的信息,我注意到如果我不使用该setDisplayedValues()方法而是直接设置整数,使用数字键盘,但这里的问题是输入的数字是它应该的10倍 - 例如,如果你在控件中输入"15",它被解释为"1.5"

        // This will allow a user to select using a number keyboard, but input needs to be 10x more than it should be. 
        np.setMinValue(0);
        np.setMaxValue(numberOfIntensityOptions-1);
        np.setFormatter(new NumberPicker.Formatter() {
            @Override
            public String format(int value) {
                return BigDecimal.valueOf(value).divide(BigDecimal.TEN).toString();
            }
        });
Run Code Online (Sandbox Code Playgroud)

有关如何提升数字键盘以允许用户输入这样的十进制数字的任何建议?

Ala*_*ore 7

我已经成功地实现了这个目标,从@ LuksProg对另一个问题的有用答案中大量借用.基本思想是搜索NumberPicker的EditText组件,然后将输入类型指定为数字.首先添加此方法(再次感谢@LuksProg):

private EditText findInput(ViewGroup np) {
    int count = np.getChildCount();
    for (int i = 0; i < count; i++) {
        final View child = np.getChildAt(i);
        if (child instanceof ViewGroup) {
            findInput((ViewGroup) child);
        } else if (child instanceof EditText) {
            return (EditText) child;
        }
    }
    return null;
}
Run Code Online (Sandbox Code Playgroud)

然后,在我的Activity的onCreate()方法中,我调用它并设置输入类型:

np.setMinValue(0);
np.setMaxValue(intensityStrings.length-1);
EditText input = findInput(np);    
input.setInputType(InputType.TYPE_CLASS_NUMBER);
Run Code Online (Sandbox Code Playgroud)

这对我有用!

  • 如果您的 setDisplayedValues() 是类似数字的字符串,则适用于 Android 6,但如果它们包含其他字符(单位,例如“1 米”、“2 米”),则会崩溃。 (2认同)