为什么我不能强制EditTextPreference只接受数字? [英] Why I can't enforce EditTextPreference to take just numbers?
问题描述
目标:使用EditTextPreference
接受用户输入的数字.
GOAL: Use EditTextPreference
to take a number input from an user.
问题::我使用的是support.v7.preference
,据我所知,该库在创建自定义DialogPreference
时会带来问题(
PROBLEM: I'm using support.v7.preference
and, from what I've understood, this library bring problems to creates a custom DialogPreference
(HowTo use support.v7.preference with AppCompat and potential drawbacks). Anyway I tried to create a NumberPickerPreference
extending DialogPreference
but I got ClassCastException
.
我还发现了另一种方法:以编程方式设置EditTextPreference
对象的输入类型,如下所示:
Also I found another approach: programmatically set the input type of an EditTextPreference
object like below:
EditTextPreference pref = (EditTextPreference) findPreference("pref_edit_text");
if (pref != null) {
pref.getEditText().setInputType(InputType.TYPE_CLASS_NUMBER);
}
没办法,我总是得到ClassCastException
.
我尝试过的最后一种方法:修改xml
Last approach I tried : modify the xml
android:inputType="numberDecimal"
android:digits="0123456789"
或android:numeric="integer"
再也没有办法,在Dialog
上我得到了完整的键盘,因此用户可以编写所有内容.
No way again, on the Dialog
I get the full keyboard, so the user can write everything.
有没有办法适当地强制EditTextReference
接受数字输入?
Is there a way to properly enforce EditTextReference
to take just number input?
推荐答案
尝试以下方法之一:
android:inputType="numberSigned"
android:inputType="phone"
android:inputType="numberDecimal|numberSigned"
android:digits="0123456789"
如果您愿意尝试的话,可以使用这个库来使它工作:
There´s this lib that is supposed to make it work, if you´re willing to try:
https://github.com/Gericop/Android-Support-Preference -V7-Fix
阅读他们的github页面,您可以找到自定义输入的示例以及它们的示例代码,这些示例看起来与您现在正在做的事情相似:
Reading their github page you can find examples of custom inputs and their example code that looks similar to what you are doing now:
该示例应用程序显示了一个示例(通过XML进行设置)和(以编程方式)查询EditTextPreference的输入类型:
"The sample app shows an example of setting (via XML) and querying (programmatically) the input type of the EditTextPreference:
<EditTextPreference
android:inputType="phone"
android:key="edit_text_test" />
EditTextPreference etPref = (EditTextPreference) findPreference("edit_text_test");
if (etPref != null) {
int inputType = etPref.getEditText().getInputType();
// do something with inputType
}
这篇关于为什么我不能强制EditTextPreference只接受数字?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!