SoFunction
Updated on 2025-04-10

Android EditTextView implements space-separated input (phone number, bank card)

Phone number input box requirements:

  • Three digits, seven digits have spaces
  • Delete the fourth to last, and the eighth position will also delete the spaces

Using TextWatcher

When an object of a type is attached to an Editable, its methods will be called when the text is changed.

Actually, it’s not difficult. After reading the examples I searched online, I thought a little bit, so I made my own record here.

import ;
import ;
import ;
import ;
/**
 * @desc
 * @autor Xemenes
 * @time 2017/5/12 10:18
 */
public class PhoneNumberTextWatcher implements TextWatcher {
  EditText editText;
  int lastContentLength = 0;
  boolean isDelete = false;
  public PhoneNumberTextWatcher(EditText editText) {
     = editText;
  }
  @Override
  public void beforeTextChanged(CharSequence s, int start, int count, int after) {
  }
  @Override
  public void onTextChanged(CharSequence s, int start, int before, int count) {
    StringBuffer sb = new StringBuffer(s);
    //Is it an input state    isDelete = () > lastContentLength ? false : true;
    //The input is the 4th and 9th bits, and you need to insert a space at this time    if(!isDelete&& (() == 4||() == 9)){
      if(() == 4) {
        (3, " ");
      }else {
        (8, " ");
      }
      setContent(sb);
    }
    //When the deleted position reaches 4 or 9, remove the space    if (isDelete && (() == 4 || () == 9)) {
      (() - 1);
      setContent(sb);
    }
    lastContentLength = ();
  }
  @Override
  public void afterTextChanged(Editable s) {
  }
  /**
    * Add or remove spaces EditText settings
    *
    * @param sb
    */
  private void setContent(StringBuffer sb) {
    (());
    //Move the cursor to the end    (());
  }
}

Summarize

The above is the Android EditTextView introduced to you by the editor. It implements space-separated input (phone number, bank card). I hope it will be helpful to everyone. If you have any questions, please leave me a message and the editor will reply to everyone in time. Thank you very much for your support for my website!