我正在按照这个例子进行:
http://developer.android.com/resources/tutorials/views/hello-autocomplete.html
我想知道如何使用ListView来实现,而不是使用已提供的下拉窗口。
例如,当用户在textView中输入时,textView下方会显示一个ListView,随着用户在textView字段中输入内容而不断更改。
编辑:这是我根据Josephus的建议编写的解决方案:
package com.jaylefler.contacts;
import java.util.ArrayList;
import android.app.Activity;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ListView;
public class ContactProjectActivity extends Activity {
/** Called when the activity is first created. */
// List of all contacts
private ArrayList<String> searchNames = new ArrayList<String>();
// Filtered list of contacts after user begins typing in search field
private ArrayList<String> partialNames = new ArrayList<String>();
// List of names matching criteria are listed here
private ListView myList;
// Field where user enters his search criteria
private EditText nameCapture;
// Adapter for myList
private ArrayAdapter<String> adapter;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// Set list adapter
myList = (ListView) findViewById(R.id.names);
adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, partialNames);
myList.setAdapter(adapter);
searchNames.add("Tom Arnold");
searchNames.add("Zeb Arnold");
searchNames.add("Dan Bateman");
searchNames.add("Tommy Canders");
searchNames.add("Elijah Arnman");
searchNames.add("Tomas Muster");
searchNames.add("Stefan Edberg");
searchNames.add("Ivan Lendl");
nameCapture = (EditText) findViewById(R.id.name);
nameCapture.setText("Tom");
AlterAdapter();
nameCapture.addTextChangedListener(new TextWatcher() {
// As the user types in the search field, the list is
@Override
public void onTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {
AlterAdapter();
}
// Not used for this program
@Override
public void afterTextChanged(Editable arg0) {
}
// Not uses for this program
@Override
public void beforeTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {
// TODO Auto-generated method stub
}
});
}
// Filters list of contacts based on user search criteria. If no information is filled in, contact list will be blank.
private void AlterAdapter() {
if (nameCapture.getText().toString().isEmpty()) {
partialNames.clear();
adapter.notifyDataSetChanged();
}
else {
partialNames.clear();
for (int i = 0; i < searchNames.size(); i++) {
if (searchNames.get(i).toString().toUpperCase().contains(nameCapture.getText().toString().toUpperCase())) {
partialNames.add(searchNames.get(i).toString());
}
adapter.notifyDataSetChanged();
}
}
}
}