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

Cách sử dụng chức năng tìm kiếm trong Custom ListView Android

Giới thiệu

Ví dụ này minh họa cách triển khai chức năng tìm kiếm (search/filter) trên một ListView tùy chỉnh trong Android. Người dùng có thể nhập từ khóa vào EditText để lọc danh sách các tháng.

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, điền đầy đủ thông tin để tạo dự án.

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

    <EditText
        android:id="@+id/etSearch"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="Tìm kiếm tại đây" />

    <ListView
        android:id="@+id/listView"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_below="@id/etSearch" />

</RelativeLayout>

Bước 3: Viết code logic (src/MainActivity.java)

import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ListView;
import java.util.ArrayList;

public class MainActivity extends AppCompatActivity {
    ListView listView;
    ArrayList<String> months = new ArrayList<>();
    ArrayAdapter<String> arrayAdapter;
    EditText etSearch;

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

        listView = findViewById(R.id.listView);
        etSearch = findViewById(R.id.etSearch);

        // Khởi tạo dữ liệu
        months.add("Tháng 1");
        months.add("Tháng 2");
        months.add("Tháng 3");
        months.add("Tháng 4");
        months.add("Tháng 5");
        months.add("Tháng 6");
        months.add("Tháng 7");
        months.add("Tháng 8");
        months.add("Tháng 9");
        months.add("Tháng 10");
        months.add("Tháng 11");
        months.add("Tháng 12");

        arrayAdapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, android.R.id.text1, months);
        listView.setAdapter(arrayAdapter);

        // Xử lý sự kiện tìm kiếm
        etSearch.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
                // Không cần xử lý
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                arrayAdapter.getFilter().filter(s);
            }

            @Override
            public void afterTextChanged(Editable s) {
                // Không cần xử lý
            }
        });
    }
}

Bước 4: Cấu hình Manifest (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ị Android thật, nhấn Run trong Android Studio. Trên thiết bị, nhập từ khóa vào ô tìm kiếm để lọc danh sách tháng.

Cách sử dụng chức năng tìm kiếm trong Custom ListView Android

Giải thích

Sử dụng ArrayAdapter có sẵn phương thức getFilter() để lọc dữ liệu. Khi người dùng gõ vào EditText, sự kiện onTextChanged được kích hoạt và gọi filter(s) với chuỗi nhập vào. Adapter sẽ tự động cập nhật ListView chỉ hiển thị các mục khớp với từ khóa.