Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
424 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 Reply

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);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

56.9k users

...