Using Android AutoCompleteTextView with ArrayAdapter<Objects> instead of ArrayAdapter<Strings>
Two ways:
Override
toString()
inStudent
class and make it returnname
. You can get the object that was selected with the following code:public static class Student { private String name; public Student(String name) { this.name = name; } @Override public String toString() { return name; } } AutoCompleteTextView tv = (AutoCompleteTextView) findViewById(R.id.autoCompleteTextView1); final ArrayList<Student> list = new ArrayList<MainActivity.Student>(); list.add(new Student("Viru")); list.add(new Student("Gauti")); ArrayAdapter<Student> adapter = new ArrayAdapter<MainActivity.Student>( this, android.R.layout.simple_dropdown_item_1line, list); tv.setAdapter(adapter); tv.setOnItemClickListener(new OnItemClickListener() { @Override public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) { Student selected = (Student) arg0.getAdapter().getItem(arg2); Toast.makeText(MainActivity.this, "Clicked " + arg2 + " name: " + selected.name, Toast.LENGTH_SHORT).show(); } });
Implement a custom adapter (by extending
BaseAdapter
class orArrayAdapter<Student>
class) Check this tutorial : http://www.ezzylearning.com/tutorial.aspx?tid=1763429
You can use an AbstractList
to get the String
representation of each item in your object list.
private void setupAutoComplete(AutoCompleteTextView view, List<T> objects) {
List<String> names = new AbstractList<String>() {
@Override
public int size() { return objects.size(); }
@Override
public String get(int location) {
return objects.get(location).getName();
}
};
view.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, names));
}