AutoCompleteTextView 是 Android 中的一个控件,它提供了自动完成文本的功能,当用户在文本框中输入内容时,它会显示匹配的建议项。以下是 AutoCompleteTextView 的基本使用步骤:

1. 在布局文件中添加 AutoCompleteTextView:

在 XML 布局文件中添加 AutoCompleteTextView 控件:
<AutoCompleteTextView
    android:id="@+id/autoCompleteTextView"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:hint="Type here..."/>

2. 准备建议项的数据源:

准备一个数据源,可以是数组、集合等,用于提供给 AutoCompleteTextView 显示建议项。
String[] suggestionArray = {"Apple", "Banana", "Cherry", "Date", "Grape", "Lemon", "Orange", "Peach"};

3. 创建适配器:

创建一个适配器,用于将数据源与 AutoCompleteTextView 绑定。
ArrayAdapter<String> adapter = new ArrayAdapter<>(this, android.R.layout.simple_dropdown_item_1line, suggestionArray);

4. 将适配器与 AutoCompleteTextView 绑定:

将创建的适配器与 AutoCompleteTextView 控件关联起来。
AutoCompleteTextView autoCompleteTextView = findViewById(R.id.autoCompleteTextView);
autoCompleteTextView.setAdapter(adapter);

完整示例:

以下是一个完整的示例代码,演示如何使用 AutoCompleteTextView:
import android.os.Bundle;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import androidx.appcompat.app.AppCompatActivity;

public class MainActivity extends AppCompatActivity {

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

        // 准备建议项的数据源
        String[] suggestionArray = {"Apple", "Banana", "Cherry", "Date", "Grape", "Lemon", "Orange", "Peach"};

        // 创建适配器
        ArrayAdapter<String> adapter = new ArrayAdapter<>(this, android.R.layout.simple_dropdown_item_1line, suggestionArray);

        // 将适配器与 AutoCompleteTextView 绑定
        AutoCompleteTextView autoCompleteTextView = findViewById(R.id.autoCompleteTextView);
        autoCompleteTextView.setAdapter(adapter);
    }
}

在这个示例中,我们创建了一个包含水果名称的建议项数组,然后使用 ArrayAdapter 将数据源与 AutoCompleteTextView 绑定。当用户在文本框中输入内容时,AutoCompleteTextView 会显示匹配的建议项。


转载请注明出处:http://www.pingtaimeng.com/article/detail/15150/Android