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

时间:2013-09-13 19:58:01

标签: 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);

作为更多信息,我注意到如果我不使用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();
            }
        });

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

2 个答案:

答案 0 :(得分:7)

我已经成功实现了这个目标,从@LuksProg's helpful answer大量借用了另一个问题。基本思想是搜索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;
}

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

np.setMinValue(0);
np.setMaxValue(intensityStrings.length-1);
EditText input = findInput(np);    
input.setInputType(InputType.TYPE_CLASS_NUMBER);

这对我有用了!

答案 1 :(得分:1)

我的答案是在Alan Moore的基础上改进,只需改变最后一行

    input.setInputType(InputType.TYPE_CLASS_NUMBER); 

    input.setRawInputType(InputType.TYPE_CLASS_NUMBER);
然后就会出现像personne3000这样的问题,没有更多的崩溃。 对不起,我的英语不好,但我希望你能理解我的意思。

相关问题