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

                }
            });
相关推荐
阿pin42 分钟前
Android随笔-SharedPreferences
android·sp
茶栀(*´I`*)2 小时前
Android 测试入门指南:ADB 基础配置与常用设备管理命令解析
android·adb
gxgldyh4 小时前
Android Framework源码解析(七):BootAnimation 启动流程解析——开机动画是如何显示出来的?
android
达达尼昂4 小时前
在 Claude Cowork 中用好 Claude Fable 5
android·人工智能·后端
sTone873755 小时前
写时复制COW的第一性理解
android·c++·flutter
sTone873755 小时前
Zygote的第一性理解
android
sTone873755 小时前
类RN框架通过Service暴露卡片渲染能力给AI Chat
android·react native
灯火不休5 小时前
Android Studio & Flutter 构建命令完全指南
android
杉氧5 小时前
Ktor 全栈之路 (5):JWT 认证全流程实战 —— 打造安全通信闭环
android·架构·kotlin
️学习的小王6 小时前
Python + MySQL 学生信息管理系统实战教程
android·python·mysql