EditText 实时计算剩余的输入字符数两种方式

时间:2024-03-22 10:50:21

记录,免得以后找代码找得❤️都累
EditText 实时计算剩余的输入字符数两种方式
一.EditText使用addTextChangedListener来实现
1.直接使用EditText的addTextChangedListener

			mEditText.addTextChangedListener( new TextWatcher() {

            private CharSequence temp;

            private int selectionStart;

            private int selectionEnd;

            @Override
            public void beforeTextChanged ( CharSequence s, int start, int count, int after ) {
                temp = s;
            }

            @Override
            public void onTextChanged ( CharSequence s, int start, int before, int count ) {

            }

            @Override
            public void afterTextChanged ( Editable editable ) {
                int detailLength = editable.length();
                mServiceLength.setText( detailLength + "/20" );
                selectionStart = mService.getTvInputContent().getSelectionStart();
                selectionEnd = mService.getTvInputContent().getSelectionEnd();
                if ( temp.length() > 20 ) {
                    editable.delete( selectionStart - 1, selectionEnd );
                    int tempSelection = selectionStart;
                    mService.getTvInputContent().setText( editable );
                    mService.getTvInputContent().setSelection( tempSelection );
                    ToastUtil.toast( "只能输入20个字" );
                }
            }
        } );

2.借助butterknife第三方库的@OnTextChanged来实现

	@OnTextChanged ( value = R.id.id_editor_detail, callback = OnTextChanged.Callback.AFTER_TEXT_CHANGED )
    public void editTextDetailChange ( Editable editable ) {
        int detailLength = editable.length();
        mIdEditorDetailFontCount.setText( detailLength + "/140" );
        if ( detailLength == 139 ) {
            islMaxCount = true;
        }
        // 不知道为什么执行俩次,所以增加一个标识符去标识
        if ( detailLength == 140 && islMaxCount ) {
            ToastUtil.toast( "只能输入140个字" );
            islMaxCount = false;
        }
    }

二.自定义View 暂无