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

Cách sử dụng AutoCompleteTextView trong ứng dụng Android?

Giới thiệu

Hướng dẫn sử dụng AutoCompleteTextView - ô nhập văn bản gợi ý tự động khi người dùng gõ, thường dùng cho tìm kiếm, chọn địa chỉ, tên món ăn, v.v.

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

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

Khởi tạo project Android Studio.

Bước 2: Giao diện AutoCompleteTextView (res/layout/activity_main.xml)

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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:layout_margin="16dp"
    android:orientation="vertical"
    tools:context=".MainActivity">
    <android.support.v7.widget.AppCompatAutoCompleteTextView
        android:id="@+id/autoTextView"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="Nhập tên trái cây"
        android:textColor="#000000"
        android:textColorHint="#000000" />
</LinearLayout>

Bước 3: Logic gợi ý (src/MainActivity.java)

package app.tutorialspoint.com.sample;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.AppCompatAutoCompleteTextView;
import android.widget.ArrayAdapter;

public class MainActivity extends AppCompatActivity {
    private String[] fruits = {"Apple", "Banana", "Cherry", "Date", "Grape", "Kiwi", "Mango", "Pear"};

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

        AppCompatAutoCompleteTextView autoTextView = findViewById(R.id.autoTextView);
        ArrayAdapter<String> adapter = new ArrayAdapter<>(this,
            android.R.layout.select_dialog_item, fruits);

        autoTextView.setThreshold(1); // Gợi ý từ ký tự đầu tiên
        autoTextView.setAdapter(adapter);
    }
}

Bước 4: AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="https://schemas.android.com/apk/res/android"
    package="app.tutorialspoint.com.sample">
    <uses-permission android:name="android.permission.VIBRATE" />
    <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õ "a" → gợi ý "Apple", gõ "b" → "Banana", v.v.

Cách sử dụng AutoCompleteTextView trong ứng dụng Android?

Tùy chỉnh nâng cao

1. Thay đổi layout item gợi ý

// Layout tùy chỉnh thay vì android.R.layout.select_dialog_item
ArrayAdapter<String> adapter = new ArrayAdapter<>(this, R.layout.custom_dropdown_item, fruits);

2. Lọc dữ liệu từ Database/Server

autoTextView.addTextChangedListener(new TextWatcher() {
    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {
        // Gọi API/search DB với từ khóa s.toString()
        // Cập nhật adapter với kết quả mới
    }
    // ... beforeTextChanged, afterTextChanged
});

3. MultiAutoCompleteTextView (nhiều mục, phân cách bằng dấu phẩy)

MultiAutoCompleteTextView multi = findViewById(R.id.multiAutoComplete);
multi.setAdapter(adapter);
multi.setTokenizer(new MultiAutoCompleteTextView.CommaTokenizer());

4. Custom Adapter cho object phức tạp

Kế thừa ArrayAdapter<T> hoặc BaseAdapter, override getView() và getFilter() để hiển thị object (VD: Contact với tên + số điện thoại).