Change android:digits programmatically

10,780

Solution 1

Adding

manual_ip.setKeyListener(DigitsKeyListener.getInstance("0123456789."));

after

manual_ip.setInputType(InputType.TYPE_CLASS_PHONE);

and nothing after

manual_ip.setInputType(InputType.TYPE_CLASS_TEXT);

solves my problem!

Solution 2

Try using InputFilter as :

    InputFilter[] digitsfilters = new InputFilter[1];
    digitsfilters[0] = new InputFilter(){

    public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {
        // TODO Auto-generated method stub
        if (end > start) {

            char[] acceptedChars = new char[]{'0', '1', '2', '3', '4', '5', '6', '7', '8', '9'};

            for (int index = start; index < end; index++) {
                if (!new String(acceptedChars).contains(String.valueOf(source.charAt(index)))) {
                return "";
                }
            }
        }
                return null;
    }
};
manual_ip= (EditText)findViewById(R.id.manual_ip);
manual_ip.setFilters(digitsfilters);
Share:
10,780
sergi
Author by

sergi

Updated on June 04, 2022

Comments

  • sergi
    sergi over 1 year

    I have this in the layout xml

    android:digits="0123456789."
    android:inputType="phone" />
    

    What I want is to be able to change it programatically and be able to change it back and forth. The inputType part is fine with

    manual_ip.setInputType(InputType.TYPE_CLASS_TEXT);
    

    or

    manual_ip.setInputType(InputType.TYPE_CLASS_PHONE);
    

    But I'm clueless with digits parts.. I need to limit the chars to "0123456789." or allow everything depending on a checkbox state.

  • Marcello Câmara
    Marcello Câmara over 4 years
    This should be accepted as best answer because you can perform a custom filter as you want! That's what I was looking for.
  • Michał Ziobro
    Michał Ziobro over 3 years
    if i set phone inputType is filters non digits and change nothing. keyListener = DigitsKeyListener.getInstance("012...") is correct way to overload android:digits operator programatically using setFilters adds I think additional filters and doesn't change inputType default behaviour