How to Limit the Data input to certain numbers only in a TextView, using setKeyListener, in Java
setKeyListener was added in API Level 1android:digits was added in API Level 1
** Normally a TextView is not editable though.
Note that for most cases this interface has been superseded by general soft input methods as defined by InputMethod;
Sets the key listener to be used with this TextView. This can be null to disallow user input. Note that this method has significant and subtle interactions with soft keyboards and other input method: see
For digits-only text entry (0,1,2,3,4,5,6,7,8.9, +, -)KeyListener.getContentType()
for important details. Calling this method will replace the current content type of the text view with the content type returned by the key listener.1. Find a TextView using ID
2. In the MainActivity.java file, add the following the to imports section.
import android.text.method.DigitsKeyListener;
//This displays a numeric key pad. Only the odd numbers 1-9 are allowed to be typed.
myTextView.setKeyListener(new DigitsKeyListener().getInstance("13579"));
//This displays a numeric key pad. Only numbers 0-9 are allowed to be typed.
myTextView.setKeyListener(new DigitsKeyListener());
//This displays a numeric key pad. Only numbers 0-9 are allowed to be typed, and the plus (+) and minus(-) signs.
myTextView.setKeyListener(new DigitsKeyListener(true,false));
//This displays a numeric key pad. Only numbers 0-9 are allowed to be typed, and one decimal point (.)
myTextView.setKeyListener(new DigitsKeyListener(false,true));
//This displays a numeric key pad. Only numbers 0-9 are allowed to be typed, and the plus (+) and minus(-) signs, and one decimal point.
myTextView.setKeyListener(new DigitsKeyListener(true,true));
//This displays a numeric key pad. Only the odd numbers 1-9 are allowed to be typed.
myTextView.setKeyListener(new DigitsKeyListener().getInstance("13579"));
5. Compile and run!
Related Articles:
Resources:
http://developer.android.com/reference/android/widget/TextView.html#setKeyListener(android.text.method.KeyListener)
http://developer.android.com/reference/android/text/method/KeyListener.html
http://forums.ouya.tv/discussion/2564/how-to-pull-up-on-screen-keyboard-with-controller-button-instead-of-trackpad
http://developer.android.com/reference/android/text/method/KeyListener.html
http://forums.ouya.tv/discussion/2564/how-to-pull-up-on-screen-keyboard-with-controller-button-instead-of-trackpad