Search code examples
androidandroid-edittext

Cyclical replacement the content of EditText with the limited length


For example, I have EditText with length limitation of two characters. When the first and second letters entered it's ok. But when we will try to enter a third letter the first letter should be replaced with it. Next letter should replace the second and so on in a circle. How can I do this one.


Solution

  • Try using TextWatcher on your edit text to achieve the goal

    editText.addTextChangedListener(new TextWatcher() {
    
            private int lastModifiedIndex = 1;
    
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
    
            }
    
            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (s.length() > 2) {
                    char toReplace = s.charAt(s.length() - 1);
                    if (lastModifiedIndex == 0) {
                        editText.setText("" + s.charAt(lastModifiedIndex) + toReplace);
                        lastModifiedIndex = 1;
                        editText.setSelection(s.length());
                    } else {
                        editText.setText("" + toReplace + s.charAt(lastModifiedIndex));
                        lastModifiedIndex = 0;
                        editText.setSelection(s.length());
                    }
                } else {
                    lastModifiedIndex = 1;
                }
            }
    
            @Override
            public void afterTextChanged(Editable s) {
    
            }
        });