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

依然范特西╮ 提交于 2021-01-29 02:50:53

问题


What is my requirement is when the user enter 10 digits,a Dot and two decimal points(0123456789.00).Once the user entered this format automatically the edit text should stop adding text into it.And the user should not enter more than one dot.

is it possible..?.need help

thanks in advance..!


回答1:


You can apply text filter to your EditText by using editText.setFilters(filter), So the method used will be like the following:

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

This will force the user to enter "dot" after entering for digits, and will force him to enter only "two digits" after the "dot".




回答2:


You can add a TextWatcher to your edit text and listen for the text editing events.




回答3:


You will be interested in TextWatcher. You would eventually do EditText.addTextChangedListener (TextWatcher) .




回答4:


I didn't try that, but it should work.

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


来源:https://stackoverflow.com/questions/30211844/how-to-stop-the-edit-text-to-add-text-when-the-required-format-text-is-entered-i

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!