我有一个ArrayAdapter
,我要附加到AutoCompleteTextView
上,每次创建ArrayAdapter时都可以包含不同的类。我想将AutoCompleteTextView的标签设置为单击视图的ID。我试图创建一个客户ArrayAdapter并覆盖getView()
,但进展不大。我至少要创建两个ArrayAdapter,所以一个OnClickListener
不会对我有多大帮助。
设置AutoCompleteTextView标记的背后想法是,我可以将所选值的ID发送到接收服务器,而不是将所选值与文本匹配。如果有更好的方法可以进行此操作,请告诉我。
谢谢!
编辑:我已修复它,但我不喜欢它的处理方式,可能有更好的方法(如我所评论),所以我没有将其标记为已解决
public class FooArrayAdapter<T> extends ArrayAdapter<T> {
private int resourceLayout;
private Context mContext;
private AutoCompleteTextView autoCompleteTextView;
public FooArrayAdapter(Context context, int resource, List<T> items, AutoCompleteTextView autoCompleteTextView) {
super(context, resource, items);
this.resourceLayout = resource;
this.mContext = context;
this.autoCompleteTextView = autoCompleteTextView;
}
@Override
public View getView(int position, final View convertView, ViewGroup parent) {
View textView = convertView;
final ListView dropdownList = (ListView) parent;
if (textView == null) {
LayoutInflater vi;
vi = LayoutInflater.from(mContext);
textView = vi.inflate(resourceLayout, null);
}
T item = getItem(position);
if (item != null) {
//TODO There should be a better way to do this instead of checking wether this class is of the right instance, use that way
final TextView adapterTextView = (TextView) textView;
if(item instanceof Product){
adapterTextView.setText(((Product) item).getName());
adapterTextView.setTag(((Product) item).getId());
}
if(item instanceof Customer){
adapterTextView.setText(((Customer) item).getName());
adapterTextView.setTag(((Customer) item).getId());
}
dropdownList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
((View)dropdownList.getParent()).setVisibility(View.GONE); //Hide the container in which the list is displayed
autoCompleteTextView.clearFocus(); //Remove the focus from this view so a click on the back button hides the keyboard
String clickedText = adapterTextView.getText().toString();
Long clickedId = (Long) adapterTextView.getTag();
autoCompleteTextView.setText(clickedText);
autoCompleteTextView.setTag(clickedId);
}
});
}
return textView;
}
}