当在其中输入所需格式的文本时,如何停止编辑文本以添加文本?

How to stop the edit text to add text,when the required format text is entered in it?

我的要求是当用户输入 10 位数字、一个点和两个小数点 (0123456789.00)。一旦用户自动输入此格式,编辑文本应停止将文本添加到 it.And 用户应该不能输入超过一个点。

是否可能..?.需要帮助

提前致谢..!

您可以将 TextWatcher 添加到您的编辑文本并监听文本编辑事件。

您将对 TextWatcher. You would eventually do EditText.addTextChangedListener (TextWatcher) 感兴趣。

我没试过,但应该可以。

final Editable text = new SpannableStringBuilder("example");
boolean stop = false;

et.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) {
        if(stop) {
            s = text;
        } else if (text.toString().equals(s.toString())) {
            stop = true;
        }
    }
});

您可以使用 editText.setFilters(filter) 将文本过滤器应用于您的 EditText,因此使用的方法如下所示:

text = (EditText) findViewById(R.id.text);
validate_text(text);

// the method validate_text that forces the user to a specific pattern
protected void validate_text(EditText text) {

    InputFilter[] filter = new InputFilter[1];
    filter[0] = new InputFilter() {

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

            if (end > start) {
                String destText = dest.toString();
                String resultingText = destText.substring(0, dstart)
                        + source.subSequence(start, end)
                        + destText.substring(dend);
                if (!resultingText
                        .matches("^\d{1,10}(\.(\d{1,2})?)?")) {
                    return "";
                } 
            }

            return null;
        }
    };
    text.setFilters(filter);
}

这将强制用户在输入数字后输入 "dot",并强制他在 "dot" 后仅输入 "two digits"。