Android EditTextView realizes the input of of telephone number and bank card with space separation

  • 2021-08-12 03:46:14
  • OfStack

Telephone number input box requirements:

There is a space after 3 digits and 7 digits Deleting the fourth and eighth digits from the bottom will also delete the space

Using TextWatcher

When an object of a type is attached to an Editable, its methods will be called when the text is changed. That is, as long as TextWatcher is set for one editable text, the method in TextWatcher will be called when the text changes.

In fact, it is not difficult. After reading the examples searched on the Internet, my thinking is around a little, and I will make a record of myself here


import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.widget.EditText;
/**
 * @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) {
    this.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);
    // Whether it is input status 
    isDelete = s.length() > lastContentLength ? false : true;
    // The input is the 4 , No. 9 Bit, when a space needs to be inserted 
    if(!isDelete&& (s.length() == 4||s.length() == 9)){
      if(s.length() == 4) {
        sb.insert(3, " ");
      }else {
        sb.insert(8, " ");
      }
      setContent(sb);
    }
    // Delete location to 4 , 9 Strip out spaces when 
    if (isDelete && (s.length() == 4 || s.length() == 9)) {
      sb.deleteCharAt(sb.length() - 1);
      setContent(sb);
    }
    lastContentLength = sb.length();
  }
  @Override
  public void afterTextChanged(Editable s) {
  }
  /**
   *  Add or remove spaces EditText Settings of 
   *
   * @param sb
   */
  private void setContent(StringBuffer sb) {
    editText.setText(sb.toString());
    // Move the cursor to the back 
    editText.setSelection(sb.length());
  }
}

Summarize


Related articles: