EditText增加addTextChangedListener后出现stackoverflower

在项目开发中,给EditText增加addTextChangedListener后出现stackoverflower问题,其实问题在于增加监听,如果超出字数,要重新对EditText赋值,但赋值又超出规定的字数,因此就陷入一个死循环

etFeature.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) {
        Editable editable = etFeature.getText();
        long sCount = editable.length();
        LogUtils.i(this,"字符长度:"+s.length());
        if (sCount > 190) {
            String str = sCount + "/200";
            if (sCount > 200) { //如果此处增加>=的判断,则会陷入死循环
                CharSequence charSequence = s.subSequence(0, 200);
                etFeature.setText(charSequence.toString());
                editable = etFeature.getText();
                Selection.setSelection(editable,editable.length());
               sCount = editable.length();
                str = "您输入特征信息已超过200个字,请精简  " + sCount + "/200";
            }
            SpannableString spannableString = new SpannableString(str);
            int spend = str.indexOf("/");
            spannableString.setSpan(new ForegroundColorSpan(
                            CommUtils.getContext().getResources().getColor(R.color.red)),
                    0, spend, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
            tvCount.setText(spannableString);
        } else {
            tvCount.setText(sCount + "/200");
        }
    }

    @Override
    public void afterTextChanged(Editable s) {

    }
});


你可能感兴趣的:(EditText增加addTextChangedListener后出现stackoverflower)