android格式edittext每4个字符后显示空格

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10252757/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-20 03:01:39  来源:igfitidea点击:

android format edittext to display spaces after every 4 characters

androidandroid-edittext

提问by user510164

Android - I want to get a number input from the user into an EditText - it needs to be separated by spaces - every 4 characters. Example: 123456781234 -> 1234 5678 1234

Android - 我想从用户输入一个数字到 EditText - 它需要用空格分隔 - 每 4 个字符。示例:123456781234 -> 1234 5678 1234

This is only for visual purpose. However i need the string without spaces for further usage.

这仅用于视觉目的。但是我需要没有空格的字符串以供进一步使用。

What is the easiest way I can do this?

我能做到这一点的最简单方法是什么?

采纳答案by waqaslam

You need to use TextWatcherto achieve visual purpose spaces.

您需要使用TextWatcher来实现视觉目的空间。

And use any simply split string by spacelogic to join it back or loop through the entire string per character wise and eliminate (char) 32from the string

并使用任何按空格逻辑简单拆分的字符串将其连接回来或循环遍历每个字符的整个字符串并(char) 32从字符串中消除

回答by Ario Singgih Permana

is this editext for credit card?
first create count variable

这是信用卡的编辑文本吗?
首先创建计数变量

int count = 0;

then put this in your oncreate(activity) / onviewcreated(fragment)

然后把它放在你的 oncreate(activity) / onviewcreated(fragment)

ccEditText.addTextChangedListener(new TextWatcher() {
    @Override
    public void beforeTextChanged(CharSequence s, int start,
                                  int count, int after) { /*Empty*/}

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

    @Override
    public void afterTextChanged(Editable s) {

        int inputlength = ccEditText.getText().toString().length();

        if (count <= inputlength && inputlength == 4 ||
                inputlength == 9 || inputlength == 14)){

            ccEditText.setText(ccEditText.getText().toString() + " ");

            int pos = ccEditText.getText().length();
            ccEditText.setSelection(pos);

        } else if (count >= inputlength && (inputlength == 4 ||
                inputlength == 9 || inputlength == 14)) {
            ccEditText.setText(ccEditText.getText().toString()
                    .substring(0, ccEditText.getText()
                            .toString().length() - 1));

            int pos = ccEditText.getText().length();
            ccEditText.setSelection(pos);
        }
        count = ccEditText.getText().toString().length();
    }
});

回答by FoamyGuy

as @waqas pointed out, you'll need to use a TextWatcher if your aim is to make this happen as the user types the number. Here is one potential way you could achieve the spaces:

正如@waqas 指出的那样,如果您的目标是在用户键入数字时实现这一点,则需要使用 TextWatcher。这是您可以实现空间的一种潜在方式:

StringBuilder s;
s = new StringBuilder(yourTxtView.getText().toString());

for(int i = 4; i < s.length(); i += 5){
    s.insert(i, " ");
}
yourTxtView.setText(s.toString());

Whenever you need to get the String without spaces do this:

每当您需要获取没有空格的字符串时,请执行以下操作:

String str = yourTxtView.getText().toString().replace(" ", "");

回答by Miltos

I have created a class that encapsulates the given behavior.

我创建了一个封装给定行为的类。

/**
 * Custom [TextWatcher] class that appends a given [separator] for every [interval].
 */
abstract class SeparatorTextWatcher(
    private val separator: Char,
    private val interval: Int
) : TextWatcher {

    private var dirty = false
    private var isDelete = false

    override fun afterTextChanged(editable: Editable?) {
        if (dirty) return

        dirty = true
        val text = editable.toString().handleSeparator()
        onAfterTextChanged(text)
        dirty = false
    }

    override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {
        // Empty
    }

    override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
        isDelete = before != 0
    }

    private fun String.handleSeparator(): String {
        val stringBuilder = StringBuilder(this)

        if (length > 0 && length.rem(interval + 1) == 0) {
            if (isDelete) {
                stringBuilder.deleteCharAt(length - 1)
            } else {
                stringBuilder.insert(length - 1, separator)
            }
        }

        return stringBuilder.toString()
    }

    /**
     * Subclasses must implement this method to get the formatted text.
     */
    abstract fun onAfterTextChanged(text: String)
}

Here's a snippet on how to use it:

这是有关如何使用它的片段:

editText.addTextChangedListener(object : SeparatorTextWatcher(' ', 4) {
            override fun onAfterTextChanged(text: String) {
                editText.run {
                    setText(text)
                    setSelection(text.length)
                }
            }
        })

回答by ashishdhiman2007

Format of text is 000 000 0000

文本格式为 000 000 0000

android edittext textwatcher format phone number like xxx-xxx-xx-xx

android edittext textwatcher 格式电话号码,如xxx-xxx-xx-xx

public class PhoneNumberTextWatcher implements TextWatcher {

private static final String TAG = PhoneNumberTextWatcher.class
        .getSimpleName();
private EditText edTxt;
private boolean isDelete;

public PhoneNumberTextWatcher(EditText edTxtPhone) {
    this.edTxt = edTxtPhone;
    edTxt.setOnKeyListener(new View.OnKeyListener() {

        @Override
        public boolean onKey(View v, int keyCode, KeyEvent event) {
            if (keyCode == KeyEvent.KEYCODE_DEL) {
                isDelete = true;
            }
            return false;
        }
    });
}

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

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

public void afterTextChanged(Editable s) {

    if (isDelete) {
        isDelete = false;
        return;
    }
    String val = s.toString();
    String a = "";
    String b = "";
    String c = "";
    if (val != null && val.length() > 0) {
        val = val.replace(" ", "");
        if (val.length() >= 3) {
            a = val.substring(0, 3);
        } else if (val.length() < 3) {
            a = val.substring(0, val.length());
        }
        if (val.length() >= 6) {
            b = val.substring(3, 6);
            c = val.substring(6, val.length());
        } else if (val.length() > 3 && val.length() < 6) {
            b = val.substring(3, val.length());
        }
        StringBuffer stringBuffer = new StringBuffer();
        if (a != null && a.length() > 0) {
            stringBuffer.append(a);
            if (a.length() == 3) {
                stringBuffer.append(" ");
            }
        }
        if (b != null && b.length() > 0) {
            stringBuffer.append(b);
            if (b.length() == 3) {
                stringBuffer.append(" ");
            }
        }
        if (c != null && c.length() > 0) {
            stringBuffer.append(c);
        }
        edTxt.removeTextChangedListener(this);
        edTxt.setText(stringBuffer.toString());
        edTxt.setSelection(edTxt.getText().toString().length());
        edTxt.addTextChangedListener(this);
    } else {
        edTxt.removeTextChangedListener(this);
        edTxt.setText("");
        edTxt.addTextChangedListener(this);
    }

}
}

回答by Phileo99

cleaner version of @Ario's answer which follows the DRY principle:

遵循 DRY 原则的@Ario 答案的更清洁版本:

private int prevCount = 0;
private boolean isAtSpaceDelimiter(int currCount) {
    return currCount == 4 || currCount == 9 || currCount == 14;
}

private boolean shouldIncrementOrDecrement(int currCount, boolean shouldIncrement) {
    if (shouldIncrement) {
        return prevCount <= currCount && isAtSpaceDelimiter(currCount);
    } else {
        return prevCount > currCount && isAtSpaceDelimiter(currCount);
    }
}

private void appendOrStrip(String field, boolean shouldAppend) {
    StringBuilder sb = new StringBuilder(field);
    if (shouldAppend) {
        sb.append(" ");
    } else {
        sb.setLength(sb.length() - 1);
    }
    cardNumber.setText(sb.toString());
    cardNumber.setSelection(sb.length());
}

ccEditText.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) {

    } 

    @Override 
    public void afterTextChanged(Editable s) {
        String field = editable.toString();
        int currCount = field.length();

        if (shouldIncrementOrDecrement(currCount, true)){
            appendOrStrip(field, true);
        } else if (shouldIncrementOrDecrement(currCount, false)) {
            appendOrStrip(field, false);
        }
        prevCount = cardNumber.getText().toString().length(); 
    } 
}); 

回答by mach

Here is a little help function. For your example you would call it with

这是一个小帮助功能。对于你的例子,你会用

addPadding(" ", "123456781234", 4);

addPadding(" ", "123456781234", 4);

/**
 * @brief Insert arbitrary string at regular interval into another string 
 * 
 * @param t String to insert every 'num' characters
 * @param s String to format
 * @param num Group size
 * @return
 */
private String addPadding(String t, String s, int num) {
    StringBuilder retVal;

    if (null == s || 0 >= num) {
        throw new IllegalArgumentException("Don't be silly");
    }

    if (s.length() <= num) {
        //String to small, do nothing
        return s;
    }

    retVal = new StringBuilder(s);

    for(int i = retVal.length(); i > 0; i -= num){
        retVal.insert(i, t);
    }
    return retVal.toString();
}

回答by Kona Suresh

change the live text while typing is some what difficult. we should handle the following issues.

在打字时更改实时文本有些困难。我们应该处理以下问题。

a. cursor position b. we should allow the user delete the entered text.

一种。光标位置 B. 我们应该允许用户删除输入的文本。

The following code handle both the issues.

以下代码处理这两个问题。

  1. Add TextWatcher to EditText, and get the text from "afterTextchanged()" and write your logic

    String str=""; int strOldlen=0;

        @Override
                public void afterTextChanged(Editable s) {
    
       str = edtAadharNumber.getText().toString();
                    int strLen = str.length();
    
    
                    if(strOldlen<strLen) {
    
                        if (strLen > 0) {
                            if (strLen == 4 || strLen == 9) {
    
                                str=str+" ";
    
                                edtAadharNumber.setText(str);
                                edtAadharNumber.setSelection(edtAadharNumber.getText().length());
    
                            }else{
    
                                if(strLen==5){
                                    if(!str.contains(" ")){
                                     String tempStr=str.substring(0,strLen-1);
                                        tempStr +=" "+str.substring(strLen-1,strLen);
                                        edtAadharNumber.setText(tempStr);
                                        edtAadharNumber.setSelection(edtAadharNumber.getText().length());
                                    }
                                }
                                if(strLen==10){
                                    if(str.lastIndexOf(" ")!=9){
                                        String tempStr=str.substring(0,strLen-1);
                                        tempStr +=" "+str.substring(strLen-1,strLen);
                                        edtAadharNumber.setText(tempStr);
                                        edtAadharNumber.setSelection(edtAadharNumber.getText().length());
                                    }
                                }
                                strOldlen = strLen;
                            }
                        }else{
                            return;
                        }
    
                    }else{
                        strOldlen = strLen;
    
    
                        Log.i("MainActivity ","keyDel is Pressed ::: strLen : "+strLen+"\n old Str Len : "+strOldlen);
                    }
    
                }
    }
    
  2. Here I am trying to add space for every four characters. After adding first space, then the length of the text is 5. so next space is after 9 characters like that.

    if (strLen== 4||strLen==9)

    1. Here another problem is cursor position, once you modify the text of the edittext, the cursor move to first place. so we need to set the cursor manually.

    edtAadharNumber.setSelection(edtAadharNumber.getText().length());

    1. My text length is only 12 characters. So I am doing manual calculations, if your text is dynamic then you write dynamic logic.
  1. 将 TextWatcher 添加到 EditText,并从“afterTextchanged()”中获取文本并编写您的逻辑

    字符串 str=""; int strOldlen=0;

        @Override
                public void afterTextChanged(Editable s) {
    
       str = edtAadharNumber.getText().toString();
                    int strLen = str.length();
    
    
                    if(strOldlen<strLen) {
    
                        if (strLen > 0) {
                            if (strLen == 4 || strLen == 9) {
    
                                str=str+" ";
    
                                edtAadharNumber.setText(str);
                                edtAadharNumber.setSelection(edtAadharNumber.getText().length());
    
                            }else{
    
                                if(strLen==5){
                                    if(!str.contains(" ")){
                                     String tempStr=str.substring(0,strLen-1);
                                        tempStr +=" "+str.substring(strLen-1,strLen);
                                        edtAadharNumber.setText(tempStr);
                                        edtAadharNumber.setSelection(edtAadharNumber.getText().length());
                                    }
                                }
                                if(strLen==10){
                                    if(str.lastIndexOf(" ")!=9){
                                        String tempStr=str.substring(0,strLen-1);
                                        tempStr +=" "+str.substring(strLen-1,strLen);
                                        edtAadharNumber.setText(tempStr);
                                        edtAadharNumber.setSelection(edtAadharNumber.getText().length());
                                    }
                                }
                                strOldlen = strLen;
                            }
                        }else{
                            return;
                        }
    
                    }else{
                        strOldlen = strLen;
    
    
                        Log.i("MainActivity ","keyDel is Pressed ::: strLen : "+strLen+"\n old Str Len : "+strOldlen);
                    }
    
                }
    }
    
  2. 在这里,我试图为每四个字符添加空间。添加第一个空格后,文本的长度为 5。因此下一个空格在 9 个字符之后。

    如果 (strLen== 4||strLen==9)

    1. 这里的另一个问题是光标位置,一旦你修改了edittext的文本,光标就会移动到第一位。所以我们需要手动设置光标。

    edtAadharNumber.setSelection(edtAadharNumber.getText().length());

    1. 我的文本长度只有 12 个字符。所以我在做手工计算,如果你的文本是动态的,那么你写动态逻辑。

回答by kike

Assuming that you know the final length of the String, you could implement a TextWatcherthis way:

假设您知道 String 的最终长度,您可以这样实现TextWatcher

override fun setUp(view: View?) {

    editText.addTextChangedListener(object : TextWatcher{
        override fun beforeTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) {
        }

        override fun onTextChanged(p0: CharSequence, p1: Int, p2: Int, p3: Int) {
            if(p2 == 0 && (p0.length == 4 || p0.length == 9 || p0.length == 14))
                editText.append(" ")
        }

        override fun afterTextChanged(p0: Editable?) {
        }
    })

You just add a space each 4-digits block. p2 == 0is to assure the user is not deleting, otherwise he/she would get stock.

您只需在每个 4 位数字块中添加一个空格。p2 == 0是为了保证用户不会删除,否则他/她会得到库存。

The code is in Kotlin, You can do it exactly the same way in Java.

代码在 Kotlin 中,您可以在 Java 中以完全相同的方式进行。

回答by Gundu Bandgar

Simple Answer

简单的答案

    YourEditText.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) {

            int len=s.toString().length();

            if (before == 0 && (len == 4 || len == 9 || len == 14 ))
                YourEditText.append(" ");
        }

        @Override
        public void afterTextChanged(Editable s) {


        }
    });