Accepting only Numerical Entry in a EditText
This one is really easy.
I’ve been working the last couple weeks with a small crew of developers under the name “Math In Pulbic” developing small math related products for Android. With a name like “Math In Public”, one of the first things we wanted to do was make it so that we could have text entry fields that accepted only numbers. Being somewhat new to Java, I was surprised at how easy this was.
Basically, just grab your EditText widget and add a NumberKeyListener as the default key listener:
MyEditText.setKeyListener(new NumberKeyListener(){
@Override
protected char[] getAcceptedChars() {
char[] numberChars = {’1′,’2′,’3′,’4′,’5′,’6′,’7′,’8′,’9′,’0′,‘.’};
return numberChars;
}
});
The getAcceptedChars() method allows you to select specifically which characters you want to allow. So you could allow basic mathematical functions (+, =, -, /, *, etc) with this method as well.
androidblogger:
By the way, have you seen that :
android:numeric=”decimal”
in the xml description file is enough to have a numerical only editText.
I struggled with doing everything by myself, and then I found that !
27 January 2009, 5:05 amMatthias Shapiro:
Well, that’s pretty handy… and much easier. Thanks!
27 January 2009, 5:33 amroland:
It helps, thank you for sharing.
4 March 2009, 3:10 amThe Lost Arts Of War:
The Lost Arts Of War…
…an interestin post over at . . ….
8 August 2010, 10:08 pm