问题
GOAL: Use EditTextPreference
to take a number input from an user.
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
.
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);
}
No way, I always get a ClassCastException
.
Last approach I tried : modify the xml
android:inputType="numberDecimal"
android:digits="0123456789"
or android:numeric="integer"
No way again, on the Dialog
I get the full keyboard, so the user can write everything.
Is there a way to properly enforce EditTextReference
to take just number input?
回答1:
You can do it by adding android: inputType = "numberPassword"
to your XML file
Then you can set your custom keyboard programmatically in your java like this:
yourEditText.setInputType(InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_VARIATION_PASSWORD);
The next thing you could do is to create a custom class:
private class YourNumericKeyboardMethod extends PasswordTransformationMethod {
@Override
public CharSequence getTransformation(CharSequence source, View view) {
return source;
}
}
The last step is to implement it to your EditText in order to make it display only the numbers:
yourEditText.setTransformationMethod(new YourNumericKeyboardMethod());
After all this steps you should get a keyboard that has only numbers from 0 to 9 on it
回答2:
Try to set inputType as the number.
android:inputType="number"
回答3:
Try one of these:
android:inputType="numberSigned"
android:inputType="phone"
EDIT:
android:inputType="numberDecimal|numberSigned"
android:digits="0123456789"
EDIT:
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
Reading their github page you can find examples of custom inputs and their example code that looks similar to what you are doing now:
"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
}
来源:https://stackoverflow.com/questions/52741046/why-i-cant-enforce-edittextpreference-to-take-just-numbers