我让AutoCompleteTextView完美运行,直到我决定使用自定义适配器,这样我就可以自定义每一行的外观 . 这是现在发生的事情:
如你所见,这个建议是错误的 . 发生的事情就像我输入的那样,它显示了正确的建议数量,但它们的实际名称是列表中的第一个 . 所以在这一点上它应该只显示一个建议,即德克萨斯A&M,但它只显示列表中的第一个 . 这是我实现我的适配器的方式 .
//setup filter
List<String> allCollegesList = new ArrayList<String>();
for(College c : MainActivity.collegeList)
{
allCollegesList.add(c.getName());
}
AutoCompleteDropdownAdapter adapter = new AutoCompleteDropdownAdapter(main, R.layout.list_row_dropdown, allCollegesList);
//the old way of using the adapter, which worked fine
//ArrayAdapter<String> adapter = new ArrayAdapter<String>(main, android.R.layout.simple_dropdown_item_1line, allCollegesList);
textView.setAdapter(adapter);
以及我的实际适配器类:
public class AutoCompleteDropdownAdapter extends ArrayAdapter<String>{
MainActivity main;
int rowLayout;
List<String> allCollegesList;
public AutoCompleteDropdownAdapter(MainActivity main, int rowLayout, List<String> allCollegesList) {
super(main, rowLayout, allCollegesList);
this.main = main;
this.rowLayout = rowLayout;
this.allCollegesList = allCollegesList;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
try{
if(convertView==null){
// inflate the layout
LayoutInflater inflater = ((MainActivity) main).getLayoutInflater();
convertView = inflater.inflate(rowLayout, parent, false);
}
// object item based on the position
String college = allCollegesList.get(position);
// get the TextView and then set the text (item name) and tag (item ID) values
TextView collegeTextView = (TextView) convertView.findViewById(R.id.dropDownText);
collegeTextView.setText(college);
collegeTextView.setTypeface(FontManager.light);
} catch (NullPointerException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
return convertView;
}
}
1 回答
这里发生的是当
AutoCompleteTextView
调用ArrayAdapter
的getFilter
方法时返回Filter
,它负责过滤ArrayAdapter
,但不过滤allCollegesList
. 当您键入第一个字符时,将调用Filter
的方法,并且ArrayAdapter
已在第一个位置(0, 1, ...
)过滤了元素 . 但是,AutoCompleteTextView
使用您的实现来获取视图 . 您使用列表就像没有进行过滤一样,并使用未过滤列表的第一个元素 .您也可以通过覆盖适配器的
getFilter
方法来过滤自己的列表 . 但那将是更多的编码而不是必要的 .您可以使用
ArrayAdapter
的方法而不是您自己的列表,而不是:使用
代替
BTW:
您也可以使用
getContext()
方法从parent
获取上下文 . 这样你可以从MainActivity
解耦适配器 .