EditText 字数限制,实时监听输入框的内容

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_39249422/article/details/88240560

布局文件

<EditText
            android:id="@+id/et_coller"
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:layout_weight="1"
            android:gravity="center_vertical"
            android:hint="请输入"
          />

在代码中初始化拿到空间

mTvNamel = (EditText) findViewById(R.id.et_coller);
mTvNamel.addTextChangedListener(textWatcher);
/**
 * 限制输入的字数
 */
TextWatcher textWatcher = new TextWatcher() {
    private CharSequence sequence;
    private int start;
    private int end;

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

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

    }

    @Override
    public void afterTextChanged(Editable s) {
        start = mTvNamel.getSelectionStart();
        end = mTvNamel.getSelectionEnd();
        if (sequence.length() >=15) {
            ToastUtils.showToast("字数限制15字");
            s.delete(start - 1, end);
            int tempSelection = start;
            mTvNamel.setText(s);
            mTvNamel.setSelection(tempSelection);
        }
    }
};

猜你喜欢

转载自blog.csdn.net/qq_39249422/article/details/88240560
今日推荐