Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Android

Cách đếm số ký tự trong EditText khi gõ trong Android

Giới thiệu

Ví dụ này minh họa cách đếm số ký tự real-time khi người dùng gõ vào EditText sử dụng TextWatcher.

Các bước thực hiện

Bước 1: Tạo dự án mới

Mở Android Studio, chọn File → New Project và điền thông tin cần thiết.

Bước 2: Thiết kế giao diện (res/layout/activity_main.xml)

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    xmlns:android="https://schemas.android.com/apk/res/android"
    xmlns:tools="https://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:padding="4dp"
    tools:context=".MainActivity">

    <EditText
        android:id="@+id/editText"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:ems="10"
        android:hint="Nhập văn bản"/>

    <TextView
        android:id="@+id/textView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_above="@+id/editText"
        android:layout_marginBottom="20dp"
        android:layout_centerInParent="true"
        android:textSize="24sp"
        android:textStyle="bold"
        android:text="Số ký tự: 0"/>

</RelativeLayout>

Bước 3: Viết code MainActivity.java

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.widget.EditText;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {
    TextView textView;
    EditText editText;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        textView = findViewById(R.id.textView);
        editText = findViewById(R.id.editText);

        editText.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
                // Cập nhật đếm trước khi thay đổi (ít dùng)
                updateCount(s.length());
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                // Cập nhật khi đang thay đổi (khuyên dùng)
                updateCount(s.length());
            }

            @Override
            public void afterTextChanged(Editable s) {
                // Sau khi thay đổi xong
            }
        });
    }

    private void updateCount(int length) {
        textView.setText("Số ký tự: " + length);
    }
}

Cách tốt hơn - dùng afterTextChanged:

@Override
public void afterTextChanged(Editable s) {
    textView.setText("Số ký tự: " + s.length());
}

Mẹo: Có thể dùng thuộc tính XML android:maxLength="100" để giới hạn ký tự tự động.

Bước 4: Cấu hình AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest
    xmlns:android="https://schemas.android.com/apk/res/android"
    package="app.com.sample">

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">

        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

    </application>
</manifest>

Chạy ứng dụng

Kết nối thiết bị, nhấn Run. Gõ văn bản vào EditText để xem bộ đếm cập nhật real-time.

Cách đếm số ký tự trong EditText khi gõ trong Android

Cách đếm số ký tự trong EditText khi gõ trong Android