Layout样式:
layout 代码:
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" tools:context=".MainActivity"> <EditText android:id="@+id/edt_intro" android:layout_width="350dp" android:paddingRight="10dp" android:layout_height="wrap_content" android:hint="输入.." android:paddingBottom="30dp" android:textSize="18dp" android:gravity="top" android:paddingTop="10dp" android:paddingLeft="10dp" android:textColor="#000000" android:textCursorDrawable="@null" android:maxLength="400" android:minHeight="100dp" android:background="@null" android:textColorHint="#707070"/> <RelativeLayout android:layout_width="match_parent" android:layout_height="wrap_content"> <TextView android:id="@+id/count" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="0/500" android:textSize="15dp" android:textColor="#707070" android:layout_marginTop="15dp" android:layout_alignParentRight="true" android:layout_marginRight="30dp"/> </RelativeLayout> </LinearLayout>
MainActivity的逻辑实现:
package com.example.counttestapplication; import androidx.appcompat.app.AppCompatActivity; import android.os.Bundle; import android.text.Editable; import android.text.TextWatcher; import android.widget.EditText; import android.widget.TextView; import android.widget.Toast; public class MainActivity extends AppCompatActivity { private EditText edt_intro; private TextView count; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); edt_intro = findViewById(R.id.edt_intro); count = findViewById(R.id.count); initEvent(); } private void initEvent() { edt_intro.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) { } @Override public void afterTextChanged(Editable s) { count.setText(String.valueOf(s.length()+"/500")); if(s.length()>=500){ Toast.makeText(MainActivity.this, "字数超过", Toast.LENGTH_SHORT).show(); } } }); } }