当前位置: 移动技术网 > 移动技术>移动开发>Android > Android 自定义输入手机号自动添加分隔符

Android 自定义输入手机号自动添加分隔符

2019年07月24日  | 移动技术网移动技术  | 我要评论

比较简单的一个控件,就是加些逻辑处理而已,以前貌似是直接监听的,封装起来方便点

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;
  }
}

使用也简单

然后效果就出来了

输入第四个的时候自动填充‘-'分隔符,然后删除的时候自动删除‘-'分隔符

以上所述是小编给大家介绍的android 自定义输入手机号自动添加分隔符,希望对大家有所帮助

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网