在Android中自动在editText中添加Dash

时间:2013-06-07 04:22:55

标签: android textwatcher

查看我的代码:

txt_HomeNo.addTextChangedListener(new TextWatcher() {

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

            boolean flag = true;
            String eachBlock[] = txt_HomeNo.getText().toString().split("-");
            for (int i = 0; i < eachBlock.length; i++) {
                if (eachBlock[i].length() > 3) {
                    flag = false;
                }
            }

            if (flag) {

                txt_HomeNo.setOnKeyListener(new OnKeyListener() {

                    @Override
                    public boolean onKey(View v, int keyCode, KeyEvent event) {

                        if (keyCode == KeyEvent.KEYCODE_DEL)
                            keyDel = 1;
                        return false;
                    }
                });

                if (keyDel == 0) {

                    if (((txt_HomeNo.getText().length() + 1) % 4) == 0) {

                        if (txt_HomeNo.getText().toString().split("-").length <= 3) {
                            txt_HomeNo.setText(txt_HomeNo.getText() + "-");
                            txt_HomeNo.setSelection(txt_HomeNo.getText().length());
                        }
                    }
                    a = txt_HomeNo.getText().toString();
                } else {
                    a = txt_HomeNo.getText().toString();
                    keyDel = 0;
                }

            } else {
                txt_HomeNo.setText(a);
            }

        }

电话号码的最大长度仅为7.当我已经输入3位数字时,它会加上破折号(这就是我想要发生的事情)但我的问题是接下来的3位数字也会附加破折号(像这样:511-871- ...我的问题是如何用下一个4位数字进行编码并加上破折号。请帮我解决一下这个。谢谢!

6 个答案:

答案 0 :(得分:11)

我认为,我可以轻松解决此问题,请查看附带的屏幕截图

  

在2位和5位后附加 / 以获取DOB。

追加和删除两者都没有出现循环问题。 enter image description here

editeTextDob.addTextChangedListener(new TextWatcher() {
            int prevL = 0;

            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                prevL = dob.getText().toString().length();
            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void afterTextChanged(Editable editable) {
                int length = editable.length();
                 if ((prevL < length) && (length == 2 || length == 5)) {
                    editable.append("/");
                }
            }
        });

答案 1 :(得分:10)

试试这个

@Override
public void afterTextChanged(Editable text) {     


    if (text.length() == 3 || text.length() == 7) {
        text.append('-');
    }


}

或所有这些

private boolean isFormatting;
private boolean deletingHyphen;
private int hyphenStart;
private boolean deletingBackward;

@Override
public void afterTextChanged(Editable text) {
    if (isFormatting)
        return;

    isFormatting = true;

    // If deleting hyphen, also delete character before or after it
    if (deletingHyphen && hyphenStart > 0) {
        if (deletingBackward) {
            if (hyphenStart - 1 < text.length()) {
                text.delete(hyphenStart - 1, hyphenStart);
            }
        } else if (hyphenStart < text.length()) {
            text.delete(hyphenStart, hyphenStart + 1);
        }
    }
    if (text.length() == 3 || text.length() == 7) {
        text.append('-');
    }

    isFormatting = false;
}

@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
    if (isFormatting)
        return;

    // Make sure user is deleting one char, without a selection
    final int selStart = Selection.getSelectionStart(s);
    final int selEnd = Selection.getSelectionEnd(s);
    if (s.length() > 1 // Can delete another character
            && count == 1 // Deleting only one character
            && after == 0 // Deleting
            && s.charAt(start) == '-' // a hyphen
            && selStart == selEnd) { // no selection
        deletingHyphen = true;
        hyphenStart = start;
        // Check if the user is deleting forward or backward
        if (selStart == start + 1) {
            deletingBackward = true;
        } else {
            deletingBackward = false;
        }
    } else {
        deletingHyphen = false;
    }
}

答案 2 :(得分:1)

使用此代码 这段代码对我有用 它会帮助你

        editText.addTextChangedListener(new TextWatcher() {
        int prevL = 0;
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            prevL = editText.getText().toString().length();
        }

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

        }

        @Override
        public void afterTextChanged(Editable s) {
            int length = s.length();
            if ((prevL < length) && (length == 2 || length == 5)) {
                String data = editText.getText().toString();
                editText.setText(data + "/");
                editText.setSelection(length + 1);


            }

        }
    });

答案 3 :(得分:1)

@techroid的答案的改进:(kotlin版本)

如果字符是字母,start始终为0,但countafter正确,而字符为数字,start,则此问题将得到解决。是正确的,而count始终为1,而after始终为0。

要测试该错误,请执行以下操作:

  • setDashMasking(yourInput, intArrayOf(3))
  • 类型:asd(这将在d后面附加破折号,因此它将变为asd-

然后尝试将其删除,除非您输入123,否则无法将其删除。@ techroid的答案将不起作用。

下面的代码将解决此问题。

    private fun setDashMasking(input: AppCompatEditText, dashIndexes: IntArray) {
        input.addTextChangedListener(object : TextWatcher {

            private var isFormatting = false
            private var deletingHyphen = false
            private var hyphenStart = 0
            private var deletingBackward = false

            override fun afterTextChanged(editable: Editable) {
                if (isFormatting) return

                isFormatting = true

                // If deleting hyphen, also delete character before or after it
                if (deletingHyphen && hyphenStart > 0) {
                    if (deletingBackward) {
                        if (hyphenStart - 1 < editable.length) {
                            editable.delete(hyphenStart - 1, hyphenStart)
                        }
                    } else if (hyphenStart < editable.length) {
                        editable.delete(hyphenStart, hyphenStart + 1)
                    }
                }

                if (!deletingHyphen &&
                    dashIndexes.contains(editable.toString().length)
                ) {
                    editable.append('-')
                }

                isFormatting = false
            }

            override fun beforeTextChanged(s: CharSequence, start: Int, count: Int, after: Int) {
                if (isFormatting) return

                // Make sure user is deleting one char, without a selection
                val selStart = Selection.getSelectionStart(s)
                val selEnd = Selection.getSelectionEnd(s)

                if (s.length > 1 // Can delete another character
                    && count - after == 1 // deleting only 1 character
                    && s[selStart - 1] == '-' // a hyphen
                    && selStart == selEnd
                ) { // no selection
                    deletingHyphen = true
                    hyphenStart = selStart - 1
                    // Check if the user is deleting forward or backward
                    deletingBackward = selStart == (selStart - 1) + 1
                } else {
                    deletingHyphen = false
                }
            }

            override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
                listener?.onChanged(s.toString())
            }
        })
    }

答案 4 :(得分:0)

太晚但可以帮助其他人

  edtMoneyIntMin.addTextChangedListener(new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {

        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
            try {
                int edtInteger = Integer.valueOf(edtMoneyIntMin.getText().toString());
                new DecimalFormat("1,000,000,000");
                String myString = NumberFormat.getInstance().format(edtInteger).replace(",", "/");
                HOUSE_COST_MIN = myString;
                txtMoneyIntMin.setText(myString);
            } catch (NumberFormatException e) {
                e.printStackTrace();
            } catch (NullPointerException e) {
                e.printStackTrace();
            }
        }

        @Override
        public void afterTextChanged(Editable s) {

        }
    });

答案 5 :(得分:0)

对于这种请求,我通常依赖于editText Masking技术。

这是一个运作良好的图书馆:

https://github.com/egslava/edittext-mask

但我最喜欢处理删除字符的是:

compile 'com.redmadrobot:inputmask:2.3.0'

它在自述文件中有一个电话号码示例。