Using Android AutoCompleteTextView with ArrayAdapter instead of ArrayAdapter

后端 未结 4 510
广开言路
广开言路 2020-12-23 17:51

I wanted to use AutoCompleteTextView in my android application.I know how to use it with simple array of Strings, but I wanted AutoCompleteTextView to use list of Objects t

4条回答
  •  抹茶落季
    2020-12-23 18:43

    Two ways:

    1. Override toString() in Student class and make it return name. 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 list = new ArrayList();
      list.add(new Student("Viru"));
      list.add(new Student("Gauti"));
      ArrayAdapter adapter = new ArrayAdapter(
              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. Implement a custom adapter (by extending BaseAdapter class or ArrayAdapter class) Check this tutorial : http://www.ezzylearning.com/tutorial.aspx?tid=1763429

提交回复
热议问题