Set edittext using only “,0123456789” programmatic

2020-08-10 07:56发布

问题:

My question is this.

I can say in xml

android:digits="0123456789,"

But this time I've to it add trough java code.

customEditText.setKeyListener(DigitsKeyListener.getInstance("0123456789,"));

Doesn't work. Application gives me same result as android:InputType="number"

So is there any alternative way to say android:digits using java?

EDITED

So my question wasn't how to get android:InputType="number" using java.

My question is that how I can get android:digits="0123456789," to be used with java.

At this point I don't care if the user can see characters. I just want my edittext field to accept only numbers from 0 to 9 and the decimal comma (,).

Because of the customEdittext is really a customized edittext I can't use xml atm.

回答1:

try customEditText.setRawInputType(InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_FLAG_DECIMAL);



回答2:

EditText ed;
ed.setInputType(InputType.TYPE_CLASS_NUMBER);

also docs may help



回答3:

According to the Android documentation TYPE_NUMBER_FLAG_DECIMAL should work http://developer.android.com/reference/android/text/InputType.html

However it doesn't, if you use only TYPE_NUMBER_FLAG_DECIMAL the user will be able to input letters as well.

But by our luck, Haresh Chaudhary, provide the correct answer, both must be use, TYPE_CLASS_NUMBER and also TYPE_NUMBER_FLAG_DECIMAL. I try hes solution and It worked.

Allthough I used setInputType instead of setRawInput:

yourEditText.setInputType(InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_FLAG_DECIMAL);


回答4:

Did you try customEditText.setRawInputType(InputType.TYPE_CLASS_NUMBER)?

Reference: InputType



回答5:

Try to add android:inputType="number" in the xml layout to your EditText (link)