你如何在 Android 上将 EditText 键盘设置为只包含数字? [英] How do you set the EditText keyboard to only consist of numbers on Android?
问题描述
我希望我的 EditText
显示一个键盘,该键盘仅有数字可见,没有其他字符.
I want my EditText
to display a keyboard that ONLY has numbers visible, no other characters.
我已经用所有可用的输入进行了测试,但它不起作用.我寻找了一种方法来获得只有数字的键盘,但我只看到了对以下内容的引用:
I have tested with all available inputs and it doesn't work. I searched for a way to get a keyboard that only has numbers but I have only seen references to:
android: inputType = "numberPassword"
但我希望数字是可见的,像这样:(numberPassword)
But I want the numbers to be visible, like this: (numberPassword)
我尝试过:
android:digits="0123456789"
android:inputType="phone"
和
android:inputType="number"
但它看起来像这样:
推荐答案
经过多次尝试,我明白了!我像这样以编程方式设置键盘值:
After several tries, I got it! I'm setting the keyboard values programmatically like this:
myEditText.setInputType(InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_VARIATION_PASSWORD);
或者,如果您愿意,您可以像这样编辑 XML:
Or if you want you can edit the XML like so:
android: inputType = "numberPassword"
两个配置都会显示密码项目符号,因此我们需要创建一个自定义的ClickableSpan
类:
Both configs will display password bullets, so we need to create a custom ClickableSpan
class:
private class NumericKeyBoardTransformationMethod extends PasswordTransformationMethod {
@Override
public CharSequence getTransformation(CharSequence source, View view) {
return source;
}
}
最后我们需要在 EditText
上实现它,以便显示输入的字符.
Finally we need to implement it on the EditText
in order to display the characters typed.
myEditText.setTransformationMethod(new NumericKeyBoardTransformationMethod());
我的键盘现在是这样的:
This is how my keyboard looks like now:
这篇关于你如何在 Android 上将 EditText 键盘设置为只包含数字?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!