setKeyListener(KeyListener)/android:digits - Limit the Data input to certain numbers only in a TextView, using setKeyListener, in Java

How to Limit the Data input to certain numbers only in a TextView, using setKeyListener, in Java

setKeyListener was added in API Level 1
android: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 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.
    For digits-only text entry (0,1,2,3,4,5,6,7,8.9, +, -)

1. Find a TextView using ID

2. In the MainActivity.java file, add the following the to imports section.

       import android.text.method.DigitsKeyListener;

3. Add the code below to the onCreate method.

    //This displays a numeric key pad. Only the odd numbers 1-9 are allowed to be typed.
    myTextView.setKeyListener(new DigitsKeyListener().getInstance("13579"));

4. Other options:

     //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: