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.