android:editText控件输入框输入达到上限后输入自动不计入

一、前言:我在写一个使用editText控件对输入的字数进行控制的功能

二、页面布局:

XML 复制代码
 <EditText
                android:id="@+id/remark"
                android:layout_width="319dp"
                android:layout_height="145dp"
                android:layout_marginStart="33dp"
                android:layout_marginTop="11dp"
                android:background="#EDEDED"
                android:inputType="textFilter"
                android:gravity="start"
                android:hint="输入备注信息"
                app:layout_constraintStart_toStartOf="parent"
                app:layout_constraintTop_toBottomOf="@+id/textView12" />

            <TextView
                android:id="@+id/num"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_alignParentRight="true"
                android:layout_alignParentBottom="true"
                android:text="0/200"
                app:layout_constraintBottom_toBottomOf="@+id/remark"
                app:layout_constraintEnd_toEndOf="@+id/remark" />

如果要使得输入的内容达到设置的值就停止呈现就需要输入这两行内容

XML 复制代码
                android:inputType="textFilter"
java 复制代码
            binding.remark.setFilters(new InputFilter[] {new InputFilter.LengthFilter(20)});

java代码

java 复制代码
 binding.remark.setFilters(new InputFilter[] {new InputFilter.LengthFilter(20)});
            binding.remark.addTextChangedListener(new TextWatcher() {

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


                }

                @Override
                public void beforeTextChanged(CharSequence s, int start, int count,
                                              int after) {


                }

                @Override
                public void afterTextChanged(Editable s) {
                    binding.num.setText(String.valueOf(s.length()) + "/20");
                    if (s.length() >= 20) {
                        Toast.makeText(getContext(), "上限了", Toast.LENGTH_SHORT).show();
                    }

                }
            });
相关推荐
三少爷的鞋2 小时前
别再这么写协程了!Marcin Moskała 剖析的 几个常见协程误区与重构
android
mmsx3 小时前
Android 防二次打包第一道锁:签名校验与完整性校验
android·kotlin
mmsx4 小时前
Android 混淆不等于安全:二次打包链路完整走一遍
android·kotlin
小宋10215 小时前
Agent轨迹级评测实战:工具选择、预算超限与回归门禁
android·网络·人工智能·回归
墨天梦7 小时前
D05_ViewModel与单向数据流
android·kotlin
蒸鱼Yuzheng9 小时前
Android 构建可复现性:APK 指纹、文件级差异与供应链审计
android·apk·devops·软件供应链·可复现构建
墨天梦11 小时前
D03_Compose列表与稳定身份
android·gitee·kotlin
萌新杰少11 小时前
Kuikly股票查看软件开发体验——SaiRen
android·kotlin·客户端
vilya11 小时前
把 Python 塞进 APK:Chaquopy 打包实践
android·python
用户928172673901611 小时前
Android Compose版本的AI组件库来了。
android·kotlin