EditText-如何以组或块的形式分隔在EditText中键入的字符 [英] EditText - How to separate characters that are typed in a EditText in groups or blocks

查看:135
本文介绍了EditText-如何以组或块的形式分隔在EditText中键入的字符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有一种方法可以在用户键入时将来自EditText的字符按块进行分组?例如:1234 4567 7890,依此类推?

Is there a way I can group characters from a EditText in blocks while the user is typing? Exemple: 1234 4567 7890 and so on?

我有一个支持数字且长度为16个字符的编辑文本,我希望将它们分组在单独的块中,以提高可视性.

I have an edit text that support numeric numbers and has 16 char length and I would like to group them in separated blocks for a better visibility.

推荐答案

    editText.addTextChangedListener(new FourDigitCardFormatWatcher(editText));

每4位添加空格.使用以下代码.

Add space for every 4 digits.Use the following code.

public class FourDigitCardFormatWatcher implements TextWatcher {

    // Change this to what you want... ' ', '-' etc..
        private final String space = " ";
        EditText et_filed;


        public FourDigitCardFormatWatcher(EditText et_filed){
            this.et_filed = et_filed;
        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
        }

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {
        }

        @Override
        public void afterTextChanged(Editable s) {
            String initial = s.toString();
            // remove all non-digits characters
            String processed = initial.replaceAll("\\D", "");

            if (processed.length() > 4){
                processed = processed.replaceAll("(\\d{4})(?=\\d)", "$1 ");
            }

            //Remove the listener
            et_filed.removeTextChangedListener(this);

            //Assign processed text
            et_filed.setText(processed);

            try {
                et_filed.setSelection(processed.length());
        } catch (Exception e) {
            // TODO: handle exception
        }

        //Give back the listener
            et_filed.addTextChangedListener(this);
        }
    }

这篇关于EditText-如何以组或块的形式分隔在EditText中键入的字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆