Android EditText InputFilter

时间:2016-01-17 15:55:26

标签: android android-input-filter

如何使用过滤器一次删除两个字符?

我正在尝试将一个简单的过滤器应用于EditText 它必须如下工作:
(希望收到格式:1234 5678 ....)

===>编辑:第一部分运作良好。

1)当EditText中有4位数字并且我输入第5位时 -
首先必须出现一个空格,然后是这个数字  2)我需要反向(在字符删除期间) -
必须用第5位删除该空格。

我的代码出了什么问题?

editText.setFilters(new InputFilter[]{new DigitsKeyListener(Boolean.FALSE, Boolean.TRUE) {

    @Override
    public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {

        //  any chars except backspace
        if (!source.equals("")) {
            if (dest.length() == 4) {
                // here I must add a space and then the source
                // ===> EDITED:
                return " " + source;
                // return super.filter(" " + source, start, end + 1, dest, dstart, dend + 1);
            } // backspace entered
        } else {
            if (dest.length() == 6) {
                // here I must delete the 6-th character 
                // and the space before
                return super.filter(source, 0, 0, dest, 5, 6);
            }
        }

        return null;
    }
}});

2 个答案:

答案 0 :(得分:0)

我建议您使用TextWatcher格式化 AdRequest request = new AdRequest(); Set<String> keywords = new HashSet<String>(); keywords.add("game"); request.setKeywords(keywords); 输入,因为EditText通常用于输入限制,以决定可以键入的内容不格式化文本。

您将使用以下代码获得所需的输出:

InputFilter

答案 1 :(得分:0)

请使用此

$moduleObject.myVar

然后使用

public class CustomFormatWatcher implements TextWatcher {

    private int size;

    public CustomFormatWatcher(int size) {
        this.size = size;
    }

    @Override
    public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

    }

    @Override
    public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

    }

    @Override
    public void afterTextChanged(Editable editable) {
        char hyphen = ' ';
        char c = 0;
        if (editable.length() > 0) {
            c = editable.charAt(editable.length() - 1);
            if (c == hyphen) {
                editable.delete(editable.length() - 1, editable.length());
            }
        }
        if (editable.length() > 0 && (editable.length() % size) == 0) {
            c = editable.charAt(editable.length() - 1);
            if (hyphen == c) {
                editable.delete(editable.length() - 1, editable.length());
            }
        }
        if (editable.length() > 0 && (editable.length() % size) == 0) {
            c = editable.charAt(editable.length() - 1);
            // Only if its a digit where there should be a space we insert a hyphen
            if (Character.isDigit(c) && TextUtils.split(editable.toString(), String.valueOf(hyphen)).length <= 3) {
                editable.insert(editable.length() - 1, String.valueOf(hyphen));
            }
        }
    }
}