Android 限定字数文本输入框的实现

本文介绍了一种在Android应用中实现EditText输入框实时字数统计的方法。通过使用TextWatcher监听器,可以动态更新显示已输入字符数量的TextView,确保用户在输入过程中了解剩余字数,适用于限制输入长度的场景。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

<RelativeLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_marginLeft="18dp"
    android:layout_marginRight="18dp">
    
    <EditText
        android:id="@+id/et_word"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="12dp"
        android:background="@drawable/bg_stroke_r2_a8a8a8"
        android:maxLength="100"
        android:paddingBottom="35dp"
        android:paddingLeft="10dp"
        android:paddingRight="10dp"
        android:paddingTop="12dp"
        android:textColor="#2e2e2e"
        android:textSize="14sp" />
        
    <TextView
        android:id="@+id/tv_word_total"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignBottom="@id/et_word"
        android:layout_alignParentRight="true"
        android:layout_marginBottom="10dp"
        android:layout_marginRight="18dp"
        android:text="/100"
        android:textColor="#999999"
        android:textSize="12sp" />
        
    <TextView
        android:id="@+id/tv_word_count"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignBottom="@id/et_word"
        android:layout_marginBottom="10dp"
        android:layout_toLeftOf="@id/tv_word_total"
        android:text="0"
        android:textColor="#ff0000"
        android:textSize="12sp" />
        
</RelativeLayout>
// bg_stroke_r2_a8a8a8.xml
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
    <stroke
        android:width="1dp"
        android:color="#a8a8a8" />
    <size
        android:width="20dp"
        android:height="10dp" />
    <corners android:radius="2dp" />
</shape>
        mTvWordCount = (TextView) findViewById(R.id.tv_word_count);
        mEtWord = (EditText) findViewById(R.id.et_word);
        mEtWord.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                mTvWordCount.setText(String.valueOf(s.length()));
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值