Restricting Android NumberPicker to Numeric Keyboard for Numeric Input (not Alpha keyboard)

守給你的承諾、 提交于 2019-11-29 11:01:18
Alan Moore

I have successfully achieved this, borrowing heavily from @LuksProg's helpful answer to another question. The basic idea is to search for the EditText component of the NumberPicker and then to assign the input type as numeric. First add this method (thanks again to @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;
}

Then, in my Activity's onCreate() method I call this and set the input type:

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

That did the trick for me!

My answer is to improve on the basis of Alan Moore, just change the last line

    input.setInputType(InputType.TYPE_CLASS_NUMBER); 

to

    input.setRawInputType(InputType.TYPE_CLASS_NUMBER);

then there will no more problem like personne3000 said, no more crashes. I'm sorry my English is not good, but I hope you can understand what I mean.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!