android format edittext to display spaces after every 4 characters

前端 未结 12 1717
傲寒
傲寒 2020-12-10 13:27

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

12条回答
  •  长情又很酷
    2020-12-10 13:51

    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();
    }
    

提交回复
热议问题