简体   繁体   English

Android使用TextWatcher格式化文本

[英]Android formatting text using TextWatcher

I want to format my entered number in the format XXXXXX/XX/XI have come up with an algorithm but its pretty crap, instead I use index to insert a / at position 6 and 9, issue comes in on the deletion, if fails to delete as soon as it reaches any of the slashes, below is my code: 我想以XXXXXX / XX / XI格式格式化输入的数字,但想出了一种算法,但是它的功能很糟糕,相反,我使用index在位置6和9插入/ ,如果删除失败,则会出现删除问题删除任何斜杠后立即删除,以下是我的代码:

@Override
        public void afterTextChanged(Editable s) {

            edt.removeTextChangedListener(this);


            if(TextUtils.isEmpty(s))
                return;

            String string  = s.toString().replace(" ", "");

            if(string.length() > 10)
                string = string.substring(0, 11);

            StringBuilder sb = new StringBuilder(string);



            if(sb.length() >= 6)
                sb.replace(6, 7, "");

            if(sb.length() >= 6 )
                sb.insert(6, "/");


            if(sb.length() >= 9)
                sb.replace(9, 10, "");

            if(sb.length() >= 9)
                sb.insert(9, "/");


            edt.setText(sb.toString());
            edt.setSelection(sb.length());
            edt.addTextChangedListener(this);

        }

Anyone got a better solution? 任何人都有更好的解决方案?

If this number formating is of a phone number try using https://github.com/googlei18n/libphonenumber 如果此号码格式是电话号码,请尝试使用https://github.com/googlei18n/libphonenumber

Otherwise you could do: 否则,您可以执行以下操作:

x = x.substring(0, 6) + "/" + x.substring(6, 9) + "/" + x.substring(9, 11);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM