我让 AutoCompleteTextView 使用默认下拉菜单。我现在正试图弄清楚是否可以使用自定义下拉菜单来处理我的数据。我感觉很接近,但我无法让下拉菜单显示。这是我想要做的。
我创建了一个自定义适配器。
public class UserSearchAdapter extends ArrayAdapter<UserSearchItem> {
private Context context;
private LayoutInflater vi;
int count = 0;
public UserSearchAdapter(Context context) {
super(context, 0, items);
this.context = context;
vi = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View v = convertView;
final UserSearchItem i = items.get(position);
if (i != null) {
Log.d("adapter", "in here");
UserSearchItem si = (UserSearchItem) i;
v = vi.inflate(R.layout.user_search_item, null);
final TextView title = (TextView) v
.findViewById(R.id.tv_userSearchName);
if (title != null)
title.setText(si.userName);
}
return v;
}
}
这是我的 UserSearchItem 类
public class UserSearchItem {
public final String userName;
public final String userId;
public final String userFBId;
public UserSearchItem(String userName, String userId, String userFBId) {
this.userName = userName;
this.userId = userId;
this.userFBId = userFBId;
}
}
这是我实现 AutoCompleteTextView 的地方
userSearch = (AutoCompleteTextView)findViewById(R.id.tv_UserSearch);
AutoCompleteAdapter = new UserSearchAdapter(this);
userSearch.setAdapter(AutoCompleteAdapter);
userSearch.addTextChangedListener(this);
@Override
public void afterTextChanged(Editable s) {
if (shouldAutoComplete) {
new DoAutoCompleteSearch().execute(s.toString());
}
}
@Override
public void beforeTextChanged(CharSequence arg0, int arg1, int arg2,
int arg3) {
// TODO Auto-generated method stub
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
shouldAutoComplete = true;
for (int position = 0; position < AutoCompleteAdapter.getCount(); position++) {
if (AutoCompleteAdapter.getItem(position).userName.equalsIgnoreCase(s.toString())) {
shouldAutoComplete = false;
break;
}
}
}
private class DoAutoCompleteSearch extends AsyncTask<String, Void, ArrayList<UserSearchItem>> {
@Override
protected ArrayList<UserSearchItem> doInBackground(String... params) {
ArrayList<UserSearchItem> autoComplete = new ArrayList<UserSearchItem>();
//get info from DB (userName, userId, userFbId)
UserSearchItem item = new UserSearchItem(userName, userId, userFbId);
autoComplete.add(item);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return autoComplete;
}
@Override
protected void onPostExecute(ArrayList<UserSearchItem> result) {
AutoCompleteAdapter.clear();
for (UserSearchItem s : result)
{
AutoCompleteAdapter.add(s);
}
}
}
有什么建议么?