android format edittext to display spaces after ev

2020-02-10 14:48发布

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

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?

10条回答
beautiful°
2楼-- · 2020-02-10 15:38

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:

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(" ", "");
查看更多
别忘想泡老子
3楼-- · 2020-02-10 15:38

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.

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.
查看更多
霸刀☆藐视天下
4楼-- · 2020-02-10 15:41

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

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();
}
查看更多
劳资没心,怎么记你
5楼-- · 2020-02-10 15:42

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

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(); 
    } 
}); 
查看更多
登录 后发表回答