在这里,我们可以使用AutoCompleteTextView来实现这个功能,它是一个扩展了EditText类的控件,允许我们在文本输入时自动提示、完成功能,这个控件使用一个Adapter来为它提供建议列表。
首先,我们需要在布局中定义AutoCompleteTextView控件:
然后,在Activity中,我们需要为这个控件设置Adapter,最好是通过异步任务来加载建议数据:
public class MainActivity extends AppCompatActivity {
private AutoCompleteTextView autoCompleteTextView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// 获取AutoCompleteTextView控件
autoCompleteTextView = (AutoCompleteTextView) findViewById(R.id.autoCompleteTextView);
// 创建一个Adapter
ArrayAdapter adapter = new ArrayAdapter(this,
android.R.layout.simple_dropdown_item_1line, new String[] { "Apple", "Banana", "Cherry", "Date", "Elderberry", "Fig", "Grape", "Kiwi", "Lemon", "Mango", "Orange", "Pear", "Quince", "Raisin", "Strawberry"});
// 为AutoCompleteTextView设置Adapter
autoCompleteTextView.setAdapter(adapter);
// 加载建议数据
new LoadDataTask().execute();
}
// 异步任务,加载建议数据
private class LoadDataTask extends AsyncTask> {
@Override
protected List doInBackground(Void... params) {
// 从网络上或本地读取建议数据
List suggestions = new ArrayList();
// ...
return suggestions;
}
@Override
protected void onPostExecute(List suggestions) {
// 创建一个Adapter
ArrayAdapter adapter = new ArrayAdapter(MainActivity.this,
android.R.layout.simple_dropdown_item_1line, suggestions