返回

在EditText中添加空格或限制字符,轻松实现文本输入格式控制

Android

添加空格

在EditText中添加空格,最简单的方法就是在文本改变时获取到原字符串,取出每一个字符,然后在每个字符后面加上一个空格,最后返回字符串并重新setText。

EditText editText = findViewById(R.id.edit_text);
editText.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 text = s.toString();
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < text.length(); i++) {
            sb.append(text.charAt(i));
            if (i < text.length() - 1) {
                sb.append(" ");
            }
        }
        editText.setText(sb.toString());
    }
});

需要注意的是,在添加空格时,光标位置可能会发生变化。因此,需要在添加空格后重新设置光标位置。

editText.setSelection(editText.getText().length());

限制字符长度

在EditText中限制字符长度,最简单的方法就是在文本改变时获取到原字符串,然后判断字符串的长度是否超过限制长度。如果超过,则截取字符串的前N个字符,最后返回字符串并重新setText。

EditText editText = findViewById(R.id.edit_text);
int maxLength = 10; // 最大字符长度
editText.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 text = s.toString();
        if (text.length() > maxLength) {
            text = text.substring(0, maxLength);
            editText.setText(text);
        }
    }
});

需要注意的是,在限制字符长度时,光标位置可能会发生变化。因此,需要在限制字符长度后重新设置光标位置。

editText.setSelection(editText.getText().length());

结语

在EditText中添加空格或限制字符,都是非常简单的操作。只需要在文本改变时获取到原字符串,然后进行相应的处理,最后返回字符串并重新setText即可。需要注意的是,在添加空格或限制字符长度时,光标位置可能会发生变化。因此,需要在操作后重新设置光标位置。