Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Android

วิธีตั้งค่า Adapter ให้ AutoCompleteTextView บน Android

ภาพรวม

AutoCompleteTextView เป็น subclass ของ EditText ที่แสดงคำแนะนำ (Suggestions) แบบ Dropdown ขณะผู้ใช้พิมพ์ ต้องตั้งค่า Adapter (แหล่งข้อมูล) และ Threshold (จำนวนตัวอักษรขั้นต่ำก่อนแสดงคำแนะนำ)

ขั้นตอนการสร้าง

ขั้นตอนที่ 1: สร้างโปรเจกต์ใหม่

Android Studio → File → New Project → Empty Activity

ขั้นตอนที่ 2: Layout (res/layout/activity_main.xml)

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:gravity="center"
    android:padding="24dp">

    <AutoCompleteTextView
        android:id="@+id/autoComplete"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="พิมพ์ชื่อภาษาโปรแกรม..."
        android:completionThreshold="1" />

</LinearLayout>

Attribute สำคัญ: android:completionThreshold="1" = แสดงคำแนะนำหลังพิมพ์ 1 ตัวอักษร

ขั้นตอนที่ 3: MainActivity.java

package com.example.myapplication;

import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import androidx.appcompat.app.AppCompatActivity;
import java.util.Arrays;
import java.util.List;

public class MainActivity extends AppCompatActivity {

    private static final String TAG = "AutoCompleteDemo";

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

        AutoCompleteTextView autoComplete = findViewById(R.id.autoComplete);

        // ข้อมูลตัวอย่าง
        List languages = Arrays.asList(
            "Android", "Java", "Kotlin", "C", "C++", "C#", 
            "Python", "JavaScript", "TypeScript", "Go", "Rust", 
            "Swift", "PHP", "HTML", "CSS", "SQL"
        );

        // สร้าง ArrayAdapter
        ArrayAdapter adapter = new ArrayAdapter<>(
            this,
            android.R.layout.simple_dropdown_item_1line, // Layout มาตรฐานของ Android
            languages
        );

        autoComplete.setAdapter(adapter);
        autoComplete.setThreshold(1); // แสดงคำแนะนำหลังพิมพ์ 1 ตัวอักษร

        // Optional: ฟังเหตุการณ์การเปลี่ยนแปลงข้อความ
        autoComplete.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) {
                Log.d(TAG, "onTextChanged: " + s);
            }
            @Override public void afterTextChanged(Editable s) {}
        });
    }
}

การปรับแต่งขั้นสูง

1. Custom Adapter (ปรับแต่งรูปลักษณ์ Dropdown)

// res/layout/dropdown_item.xml
<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="https://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:padding="16dp"
    android:textSize="16sp"
    android:textColor="#333"
    android:background="?android:attr/selectableItemBackground" />

// ใน Activity
ArrayAdapter adapter = new ArrayAdapter<>(
    this, R.layout.dropdown_item, languages
);

2. Filter แบบ Custom (เช่น ค้นหาไม่สนใจตัวพิมพ์เล็ก/ใหญ่)

ArrayAdapter adapter = new ArrayAdapter(this, 
    android.R.layout.simple_dropdown_item_1line, languages) {
    @Override
    public Filter getFilter() {
        return new Filter() {
            @Override
            protected FilterResults performFiltering(CharSequence constraint) {
                FilterResults results = new FilterResults();
                if (constraint == null || constraint.length() == 0) {
                    results.values = languages;
                    results.count = languages.size();
                } else {
                    List filtered = new ArrayList<>();
                    String filterPattern = constraint.toString().toLowerCase().trim();
                    for (String item : languages) {
                        if (item.toLowerCase().contains(filterPattern)) {
                            filtered.add(item);
                        }
                    }
                    results.values = filtered;
                    results.count = filtered.size();
                }
                return results;
            }
            @Override
            protected void publishResults(CharSequence constraint, FilterResults results) {
                clear();
                if (results.values != null) {
                    addAll((List) results.values);
                }
                notifyDataSetChanged();
            }
        };
    }
};

3. ใช้กับ Chip (Material Design)

สำหรับ UI แบบ Tag/Chip ใช้ com.google.android.material.chip.ChipGroup + Chip แทน

การทดสอบ

รันแอป → พิมพ์ "j" → จะแสดง "Java", "JavaScript" → พิมพ์ "c" → แสดง "C", "C++", "C#", "CSS"

สรุป

  • AutoCompleteTextView = EditText + Dropdown Suggestions
  • ต้องตั้งค่า Adapter (ArrayAdapter, CursorAdapter, Custom Adapter)
  • Threshold ควรตั้ง 1-2 ตัวอักษร เพื่อ UX ที่ดี
  • สำหรับข้อมูลเยอะ ควรใช้ Custom Filter หรือ load แบบ Async