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

Cách sử dụng lớp TextWatcher trong Android

Giới thiệu

Ví dụ này minh họa cách sử dụng TextWatcher để theo dõi thay đổi văn bản trong EditText theo thời gian thực.

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"
    tools:context=".MainActivity">

    <TextView
        android:id="@+id/text"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Android Text Watcher"
        android:textSize="16sp"
        android:textStyle="bold"
        android:layout_marginTop="24sp"
        android:layout_centerHorizontal="true"
        android:layout_alignParentTop="true" />

    <EditText
        android:id="@+id/etInput"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_below="@id/text"
        android:maxLength="15"
        android:hint="Nhập văn bản" />

    <TextView
        android:id="@+id/textView"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:textSize="24sp"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="12dp"
        android:layout_below="@id/etInput"/>

</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;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {
    EditText input;
    TextView output;

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

        input = findViewById(R.id.etInput);
        output = findViewById(R.id.textView);
        input.addTextChangedListener(textWatcher);
    }

    TextWatcher textWatcher = new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            // Gọi trước khi văn bản thay đổi
        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
            // Gọi khi văn bản đang thay đổi
            output.setText(s);
            
            // Ví dụ: Cảnh báo khi đạt giới hạn ký tự
            if (start == 12) {
                Toast.makeText(getApplicationContext(), "Đã đạt giới hạn tối đa", Toast.LENGTH_SHORT).show();
            }
        }

        @Override
        public void afterTextChanged(Editable s) {
            // Gọi sau khi văn bản đã thay đổi
            // Có thể dùng để validate hoặc format văn bản
        }
    };
}

Giải thích 3 phương thức:

  • beforeTextChanged(): Trước khi thay đổi - có thể lấy trạng thái cũ
  • onTextChanged(): Đang thay đổi - thích hợp để cập nhật UI real-time
  • afterTextChanged(): Sau khi thay đổi - an toàn để chỉnh sửa Editable

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 và nhập văn bản vào EditText để xem TextView cập nhật real-time.

Cách sử dụng lớp TextWatcher trong Android

Cách sử dụng lớp TextWatcher trong Android