Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
421 views
in Technique[技术] by (71.8m points)

android - How do I restrict my EditText input to numerical (possibly decimal and signed) input?

I have read Android: Limiting EditText to numbers and How do I show the number keyboard on an EditText in android?. Unfortunately, none of them seems to fit my needs.

I want to restrict my EditText input to only numbers. However, I also want to allow signed and/or decimal input.

Here is my current code (I need to do this programmatically):

EditText edit = new EditText(this);

edit.setHorizontallyScrolling(true);
edit.setInputType(InputType.TYPE_CLASS_NUMBER);

With this, my EditText merrily restricts all input to numerical digits. Unfortunately, it doesn't allow anything else, like the decimal point.

If I change that line to edit.setInputType(InputType.TYPE_NUMBER_FLAG_DECIMAL), the EditText accepts all input (which isn't what I want...).

I've tried combining flags (in desperation to see if it would work):

edit.setInputType(InputType.TYPE_CLASS_NUMBER);
edit.setInputType(InputType.TYPE_NUMBER_FLAG_DECIMAL)
edit.setInputType(InputType.TYPE_NUMBER_FLAG_SIGNED)

That didn't work either (the EditText accepted all input as usual).

So, how do I do this?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

There's no reason to use setRawInputType(), just use setInputType(). However, you have to combine the class and flags with the OR operator:

edit.setInputType(InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_FLAG_DECIMAL | InputType.TYPE_NUMBER_FLAG_SIGNED);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...