如何在运行时更改EditText字符串格式?

时间:2018-03-15 11:41:04

标签: android android-edittext

我有EditText输入IBAN号码。我想格式化

TR330006100519786457841326

当用户输入我想要的输入时,它就像

TR33 0006 1005 1978 6457 8413 26

所以基本上我想在每4位数之后添加空格

我尝试使用TextWatcher,当char sequence length点击4时我正在强制占用空间但是当用户放置“空格”时它不起作用

4 个答案:

答案 0 :(得分:2)

以下是基本字符串方式:

String input = "TR330006100519786457841326";
input = input.replaceAll("(\\w{4})", "$1 ");
System.out.println(input);

TR33 0006 1005 1978 6457 8413 26

在文本观察器中,您可以将字符串替换为上述正则表达式替换产生的输出。

final EditText editText = (EditText) findViewById(R.id.text1);

editText.addTextChangedListener(new TextWatcher() {
    public void onTextChanged(CharSequence s, int start, int before, int count) {
        String input = editText.getText().toString();
        input = input.replaceAll("(\\w{4})", "$1 ");
        editText.setText(input);
    }
});

答案 1 :(得分:2)

尝试使用以下正则表达式:

input.replaceAll("....", "$0 ");

答案 2 :(得分:0)

使用此方法

    public static String insertSeperator(String text, String insert, int period) {// text= data, insert= <the data you want to be insert>, period= <Position>
text=text.replaceAll(" ","");

    StringBuilder builder = new StringBuilder(
            text.length() + insert.length() * (text.length() / period) + 1);

    int index = 0;
    String prefix = "";
    while (index < text.length()) {
        // Don't put the insert in the very first iteration.
        // This is easier than appending it *after* each substring
        builder.append(prefix);
        prefix = insert;
        builder.append(text.substring(index, Math.min(index + period, text.length())));
        index += period;
    }
    return builder.toString();
}

答案 3 :(得分:0)

            @Override
            public void afterTextChanged(Editable s) {

                if(s.length() == 4 ||s.length() == 9 ||s.length() == 14 ||s.length() == 19 ||s.length() == 23 ||s.length() == 29 ){

                    ediTextIban.append(" ");



                }

            }