bho*_*242 11 java android android-edittext onitemclicklistener
我正在使用自动完成文本视图,它显示了数据库中的一些名称.我想在textview中显示一个名称,我从自动完成textview中选择了一个名称.这是我的代码:
ArrayList<String> s1 = new ArrayList<String>();
for (StudentInfo cn : studentInfo) {
s1.add(cn.getName());
}
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_dropdown_item_1line,s1);
a1.setThreshold(1);
a1.setAdapter(adapter);
Run Code Online (Sandbox Code Playgroud)
a1.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
}
});
Run Code Online (Sandbox Code Playgroud)
Ste*_*ter 17
试试这种方式:
AutoCompleteTextView a1 = (AutoCompleteTextView) findViewById(...);
StudentInfo[] s1 = studentInfo.toArray(new StudentInfo[studentInfo.size()]);
ArrayAdapter<StudentInfo> adapter = new ArrayAdapter<StudentInfo>(this, android.R.layout.simple_dropdown_item_1line, s1);
a1.setAdapter(adapter);
a1.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View arg1, int position, long arg3) {
Object item = parent.getItemAtPosition(position);
if (item instanceof StudentInfo){
StudentInfo student=(StudentInfo) item;
doSomethingWith(student);
}
}
});
Run Code Online (Sandbox Code Playgroud)
ArrayAdapter使用StudentInfo的toString()方法生成显示的文本,因此您需要实现一个很好的toString方法.
这样,这种实现可以适应任何对象类型.
顺便说一句:我更喜欢android.R.layout.simple_spinner_dropdown_item而不是android.R.layout.simple_dropdown_item_1line
感谢斯蒂芬·里希特!我想补充一点,List<T>在构造适配器时可以直接使用:
AutoCompleteTextView autoCompleteTextView = dialogView.findViewById(R.id.autoComplete);
// Where mStudentsInfo is List<StudentInfo>
ArrayAdapter<StudentInfo> adapter = new ArrayAdapter<>(this, android.R.layout.simple_dropdown_item_1line, mStudentsInfo);
autoCompleteTextView.setAdapter(adapter);
autoCompleteTextView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Object item = parent.getItemAtPosition(position);
if (item instanceof StudentInfo) {
StudentInfo studentInfo = (StudentInfo) item;
// do something with the studentInfo object
}
}
});
Run Code Online (Sandbox Code Playgroud)
并且也不要忘记重写以下toString()方法StudentInfo.class:
public class StudentInfo {
....
@Override
public String toString() {
return studentName;
}
}
Run Code Online (Sandbox Code Playgroud)
你的s1包含所有的名字database
a1.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> arg0, View arg1, int position,
long arg3) {
Log.d("your selected item",""+s1.get(position));
//s1.get(position) is name selected from autocompletetextview
// now you can show the value on textview.
}
});
Run Code Online (Sandbox Code Playgroud)
希望这对你有帮助,
| 归档时间: |
|
| 查看次数: |
40752 次 |
| 最近记录: |