使用Android AutoCompleteTextView和ArrayAdapter <Objects>而不是ArrayAdapter <Strings>

我想在我的android应用程序中使用AutoCompleteTextView。我知道如何使用简单的string数组,但我希望AutoCompleteTextView使用对象列表来执行完成。我的代码如下:

活动代码

public void onCreate(Bundle savedInstanceState) { // TODO Auto-generated method stub super.onCreate(savedInstanceState); setContentView(R.layout.search); initialize(); ArrayAdapter<Student> adapter = new ArrayAdapter<Student>(this, R.layout.dropdown_list_item, GetAllStudentsList()); searchBox.setAdapter(adapter); searchBox.setThreshold(THRESHOLD_VALUE); searchBox.setTextColor(Color.BLACK); } searchBox.setOnItemClickListener(new OnItemClickListener() { @Override public void onItemClick(AdapterView<?> adapterView, View view, int position, long arg3) { //Here i will grab the Student object that user selected from drop-down } }); public ArrayList<Movies> GetAllStudentsList() { //This method returns a ArrayList of <Student> type objects } 

学生类对象具有关于学生的信息,即ID,NAME,ADDRESS,MARKS

我知道AutoCompleteTextView需要一个stringtypes对象的数组来执行search操作。在我的情况下,我希望AutoCompleteTextView使用我的ArrayList基于Student对象字段NAME执行完成。我不知道如何指定AutoCompleteTextView使用NAME字段学生对象。请帮助我提供任何链接或一个小例子。

谢谢

Related of "使用Android AutoCompleteTextView和ArrayAdapter <Objects>而不是ArrayAdapter <Strings>"

两种方式:

  1. 覆盖Student类中的toString()并使其返回name 。 你可以得到用下面的代码select的对象:

      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(); } }); 
  2. 实现自定义适配器(通过扩展BaseAdapter类或ArrayAdapter<Student>类)检查本教程: http : BaseAdapter

您可以使用AbstractList来获取对象列表中每个项目的String表示forms。

 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)); }