1

I need to get an input of 9 uppercase letters separated by dash like AAA-AAA-AAA and this input has to be formatted while is entered.

Thanks in advance.

Haresh Chhelana
  • 24,394
  • 5
  • 55
  • 67
backslash17
  • 5,153
  • 4
  • 30
  • 46
  • 1
    this post may help you http://stackoverflow.com/questions/5947674/custom-format-edit-text-input-android – Giru Bhai Jun 10 '14 at 17:19

2 Answers2

3

I have found the solution using a TextWatcher. I'm using

android:inputType="textCapCharacters|textNoSuggestions"

for the EditText input type in order to receive only uppercase letters.

        txtCode = (EditText) findViewById(R.id.txtCode);

        txtCode.addTextChangedListener( new TextWatcher() {
            boolean isEdiging;
            @Override 
            public void onTextChanged(CharSequence s, int start, int before, int count) { }
            @Override 
            public void beforeTextChanged(CharSequence s, int start, int count, int after) { }


            @Override
            public void afterTextChanged(Editable s) {
                if(isEdiging) return;
                isEdiging = true;
                // removing old dashes
                StringBuilder sb = new StringBuilder();
                sb.append(s.toString().replace("-", ""));

                if (sb.length()> 3)
                    sb.insert(3, "-");
                if (sb.length()> 7)
                    sb.insert(7, "-");
                if(sb.length()> 11)
                    sb.delete(11, sb.length());

                s.replace(0, s.length(), sb.toString());
                isEdiging = false;
            }
        });
backslash17
  • 5,153
  • 4
  • 30
  • 46
  • Modifying the editable directly -- rather then calling setText on the EdtiText --- is a great approach, as it simplifies setting the cursor. – stevehs17 Mar 21 '16 at 20:51
2

You can do this by text change listner

when text_size%3==0 insert "-" character

Vibhor Bhardwaj
  • 2,951
  • 5
  • 27
  • 47