Ans*_*hul 26 android autocomplete android-adapter android-view
我想在我的android应用程序中使用AutoCompleteTextView.我知道如何使用简单的字符串数组,但我希望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
}
Run Code Online (Sandbox Code Playgroud)
学生班对象有关于学生的信息ID,NAME,ADDRESS,MARKS
.
我知道AutoCompleteTextView需要一个String类型对象的数组来执行搜索操作.在我的情况下,我希望AutoCompleteTextView使用我的ArrayList在Student对象字段NAME的基础上执行完成.我不知道如何指定AutoCompleteTextView使用NAME字段学生对象.请帮我提供任何链接或一个小例子.
谢谢
Sam*_*eer 77
两种方式:
toString()
在Student
类中重写并使其返回name
.您可以使用以下代码获取所选对象:
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();
}
});
Run Code Online (Sandbox Code Playgroud)实现自定义适配器(通过扩展BaseAdapter
类或ArrayAdapter<Student>
类)检查本教程:http://www.ezzylearning.com/tutorial.aspx?tid = 1763429
您可以使用 anAbstractList
来获取String
对象列表中每个项目的表示。
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));
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
35389 次 |
最近记录: |