Android 限定字數文本輸入框的實現

<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) {

            }
        });
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章