I am impressed with Android. I faced some situations which seemed to need some detailed care but Android has very simple solutions to those. Setting the EditText to accept only numbers is one of them. I was going to do what I usually do with Java, create my own NumberField class that extends JTextField and add method to check if the values are numeric, as well as perform other numerical operations or use a listener to validate the field when they are entered.
Android has a very simple solution for this. When implemented, the user will not even be able to type in any text in that field at all.
In the XML file where you create and set properties of the EditText field, add the following item:
android:numeric="decimal|signed"
This will let the user enter any number - integer, decimal as well as signed negative numbers but no text. The user will be able to enter only one '.' in the field which is the decimal. Pretty neat isn't it? Especially for the app that I am working on that has numerous fields that are need to be numeric only. As some of the fields in my app are created using codes, I had to set those properties in my code. The way to do that is:
textEntry.setInputType(InputType.TYPE_CLASS_NUMBER|InputType.TYPE_NUMBER_FLAG_DECIMAL|InputType.TYPE_NUMBER_FLAG_SIGNED);
Hope this is useful. Will post more ideas and tips in the next posts.