Android 사용자 정의 핸드폰 번호 입력 자동 구분자 추가

2825 단어 android구분자
비교적 간단 한 컨트롤 은 논리 적 처 리 를 더 하 는 것 일 뿐 입 니 다.예전 에는 직접 감청 한 것 같 아서 포장 하기에 편리 합 니 다.

public class AccountTxtView extends android.support.v7.widget.AppCompatEditText {
  private final char CUT = '-';
  public AccountTxtView(Context context) {
    super(context);
  }
  public AccountTxtView(Context context, AttributeSet attrs) {
    super(context, attrs);
  }
  public AccountTxtView(Context context, AttributeSet attrs, int defStyleAttr) {
    super(context, attrs, defStyleAttr);
  }
  @Override
  protected void onTextChanged(CharSequence text, int start, int lengthBefore, int lengthAfter) {
    if (text == null || text.length() == 0)
      return;
    StringBuilder sb = new StringBuilder();
    for (int i = 0; i < text.length(); i++) {//     
      if (i != 3 && i != 8 && text.charAt(i) == CUT) {
        continue;
      } else {
        sb.append(text.charAt(i));
        if ((sb.length() == 4 || sb.length() == 9)
            && sb.charAt(sb.length() - 1) != CUT) {
          sb.insert(sb.length() - 1, CUT);
        }
      }
    }
    //       
    if (!sb.toString().equals(text.toString())) {
      int index = start + 1;
      if (sb.charAt(start) == CUT) {
        if (lengthBefore == 0) {
          index++;
        } else {
          index--;
        }
      } else {
        if (lengthBefore == 1) {
          index--;
        }
      }
      setText(sb.toString());
      setSelection(index);
    }else{//      
      String line = text.subSequence(text.length() - 1, text.length()).toString();
      if (line.equals(String.valueOf(CUT))) {//      ‘-'  ,     
        sb.deleteCharAt(text.subSequence(0, text.length() - 1).length());
        setText(sb.toString());
        setSelection(sb.length());
      }
    }
  }
  public String getPhone() {
    String result = null;
    String val = getText().toString();
    if (val == null || val.isEmpty())
      return "";
    result = val.replace(String.valueOf(CUT), "");
    return result;
  }
}
사용 도 간단 하 다

그리고 효과 가 나 왔어요.

네 번 째 입력 시'-'구분자 자동 채 우기'-'구분자 자동 삭제'-'구분자
위 에서 말 한 것 은 편집장 이 소개 한 안 드 로 이 드 사용자 정의 입력 핸드폰 번호 에 자동 으로 구분자 가 추 가 됩 니 다.여러분 에 게 도움 이 되 기 를 바 랍 니 다.궁금 한 점 이 있 으 면 메 시 지 를 남 겨 주세요.편집장 은 바로 답 해 드 리 겠 습 니 다.여기 서도 저희 사이트 에 대한 여러분 의 지지 에 감 사 드 립 니 다!

좋은 웹페이지 즐겨찾기