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

                }
            });
相关推荐
符哥20082 小时前
新能源智能充电桩与 Android/iOS App 蓝牙通信协议
android·ios
JMchen1233 小时前
自定义View性能优化:从60fps到120fps的进阶之路
android·经验分享·性能优化·kotlin·自定义view
vistaup3 小时前
DevEco Studio 鸿蒙 HAR本地引入相互依赖问题解决
android·华为·harmonyos
常利兵4 小时前
Android 开发秘籍:用Tint为Icon动态变色
android
奔跑吧 android4 小时前
【车载audio】【CarAudioService 05】【车载 Android 系统调试深度指南:解析 dumpsys car_service】
android·audio·audioflinger·aosp15·车载音频·车载audio·car_service
shuangrenlong5 小时前
androidstudio gradle文件报红
android
Digitally5 小时前
如何通过蓝牙将 iPhone 上的照片传输到 Android
android·ios·iphone
常利兵5 小时前
Android Intent.setAction失效报错排查与修复全方案
android
低调小一5 小时前
RecyclerView 缓存与复用机制:从一次滑动讲明白(2026 版)
android·recyclerview
耶叶5 小时前
kotlin的修饰符
android·开发语言·kotlin