5

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.

Cœur
  • 37,241
  • 25
  • 195
  • 267
sergi
  • 1,049
  • 2
  • 12
  • 22
  • checkout this link for working answer: https://stackoverflow.com/a/65073302/6086086 – Asad Nov 30 '20 at 12:09

3 Answers3

9

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!

sergi
  • 1,049
  • 2
  • 12
  • 22
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);
ρяσѕρєя K
  • 132,198
  • 53
  • 198
  • 213
  • This should be accepted as best answer because you can perform a custom filter as you want! That's what I was looking for. – Marcello Câmara May 29 '19 at 13:12
  • 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 – Michał Ziobro Jun 02 '20 at 10:48
0

just write down this.

myEditText.setFilters( new InputFilter[] {
    new PasswordCharFilter(), new InputFilter.LengthFilter(20)});

OR

TextView editEntryVew = new TextView(...);
InputFilter[] FilterArray = new InputFilter[1];
FilterArray[0] = new InputFilter.LengthFilter(8);
editEntryView.setFilters(FilterArray);
ckpatel
  • 1,926
  • 4
  • 18
  • 34