12

有什么简单的方法可以将 2 TextView 下拉菜单设置为 AutoCompleteTextView。

android.R.layout.two_line_list_item找不到任何如何使用的示例。

所以,我尝试了这个:

public class TwoLineDropdownAdapter extends BaseAdapter {

    private LayoutInflater mInflater = null;
    private Activity activity;
    public ArrayList<TwoLineDropDown> values = new ArrayList<TwoLineDropDown>();

    public TwoLineDropdownAdapter(Activity a, ArrayList<TwoLineDropDown> items) {

        values = items;
        activity = a;
        mInflater = (LayoutInflater) activity
                .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    }

    public int getCount() {

        return values.size();
    }

    public TwoLineDropDown getItem(int position) {

        return values.get(position);
    }

    public long getItemId(int position) {

        return position;
    }

    public static class ViewHolder {

        public TextView title;
        public TextView description;
    }

    public View getView(final int position, View convertView, ViewGroup parent) {

        ViewHolder holder;

        if (convertView == null) {

            holder = new ViewHolder();

            convertView = mInflater.inflate(R.layout.dropdown_text_twoline,
                    parent, false);
            holder.title = (TextView) convertView
                    .findViewById(R.id.text1);
            holder.description = (TextView) convertView
                    .findViewById(R.id.text2);

            convertView.setTag(holder);
        } else {
            holder = (ViewHolder) convertView.getTag();
        }

        return convertView;
    }

    public void add(TwoLineDropDown ei) {

        values.add(ei);
    }
}

但我在这里遇到一个问题:

TwoLineDropdownAdapter AutoCompleteAdapter = new TwoLineDropdownAdapter(this, items);
myAutoComplete.setAdapter(AutoCompleteAdapter);

在设置适配器时它说:

绑定不匹配:AutoCompleteTextView 类型的通用方法 setAdapter(T) 不适用于参数 (TwoLineDropdownAdapter)。推断的类型 TwoLineDropdownAdapter 不是有界参数的有效替代品

如何解决这个问题?

谢谢你

4

6 回答 6

22

这里的代码为我工作,

将此适配器设置为autocompletetextview

AutoCompleteTextView etProductSearch = (AutoCompleteTextView)getView().findViewById(R.id.edtSearchBoxTakeOrder);
ProductSearchAdapter adapter = new ProductSearchAdapter(getActivity(), android.R.layout.simple_dropdown_item_1line, productList);
etProductSearch.setAdapter(adapter );

ProductSearchAdapter 类

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Filter;
import android.widget.TextView;

public class ProductSearchAdapter extends ArrayAdapter<ProductDataModel> {
    private ArrayList<ProductDataModel> items;
    private ArrayList<ProductDataModel> itemsAll;
    private ArrayList<ProductDataModel> suggestions;
    private int viewResourceId;

    @SuppressWarnings("unchecked")
    public ProductSearchAdapter(Context context, int viewResourceId,
            ArrayList<ProductDataModel> items) {
        super(context, viewResourceId, items);
        this.items = items;
        this.itemsAll = (ArrayList<ProductDataModel>) items.clone();
        this.suggestions = new ArrayList<ProductDataModel>();
        this.viewResourceId = viewResourceId;
    }

    public View getView(int position, View convertView, ViewGroup parent) {
        View v = convertView;
        if (v == null) {
            LayoutInflater vi = (LayoutInflater) getContext().getSystemService(
                    Context.LAYOUT_INFLATER_SERVICE);
            v = vi.inflate(viewResourceId, null);
        }
        ProductDataModel product = items.get(position);
        if (product != null) {
              TextView productLabel = (TextView)  v.findViewById(android.R.id.text1);
            if (productLabel != null) {
                productLabel.setText(product.getProductName());
            }
        }
        return v;
    }

    @Override
    public Filter getFilter() {
        return nameFilter;
    }

    Filter nameFilter = new Filter() {
        public String convertResultToString(Object resultValue) {
            String str = ((ProductDataModel) (resultValue)).getProductName();
            return str;
        }

        @Override
        protected FilterResults performFiltering(CharSequence constraint) {
            if (constraint != null) {
                suggestions.clear();
                for (ProductDataModel product : itemsAll) {
                    if (product.getProductName().toLowerCase()
                            .startsWith(constraint.toString().toLowerCase())) {
                        suggestions.add(product);
                    }
                }
                FilterResults filterResults = new FilterResults();
                filterResults.values = suggestions;
                filterResults.count = suggestions.size();
                return filterResults;
            } else {
                return new FilterResults();
            }
        }

        @Override
        protected void publishResults(CharSequence constraint,
                FilterResults results) {
            @SuppressWarnings("unchecked")
            ArrayList<ProductDataModel> filteredList = (ArrayList<ProductDataModel>) results.values;
            if (results != null && results.count > 0) {
                clear();
                for (ProductDataModel c : filteredList) {
                    add(c);
                }
                notifyDataSetChanged();
            }
        }
    };

}
于 2013-11-13T10:49:49.567 回答
9

根据文档,在 AutoCompleteTextView 中推断的 setAdapter 类型是:

<T extends ListAdapter & Filterable> void setAdapter(T adapter)

您的适配器必须是 ListAdapter(BaseAdapter 是,到目前为止还不错)和 Filterable,BaseAdapter 不是,您的 Adapter 实现也不是。我会扩展一个 ArrayAdapter,它是可过滤的,更不用说会简化你的实现(你的一些方法重复 ArrayAdapter 的方法以获得相同的结果):

public class TwoLineDropdownAdapter extends ArrayAdapter<TwoLineDropDown> {

    private LayoutInflater mInflater = null;
    private Activity activity;

    public TwoLineDropdownAdapter(Activity a, ArrayList<TwoLineDropDown> items) {
        super(a, 0, items);
        activity = a;
        mInflater = (LayoutInflater) activity
                .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    }

    public static class ViewHolder {

        public TextView title;
        public TextView description;
    }

    public View getView(final int position, View convertView, ViewGroup parent) {

        ViewHolder holder;

        if (convertView == null) {

            holder = new ViewHolder();

            convertView = mInflater.inflate(R.layout.dropdown_text_twoline,
                    parent, false);
            holder.title = (TextView) convertView
                    .findViewById(R.id.text1);
            holder.description = (TextView) convertView
                    .findViewById(R.id.text2);

            convertView.setTag(holder);
        } else {
            holder = (ViewHolder) convertView.getTag();
        }

        return convertView;
    }
}
于 2013-06-06T12:54:40.953 回答
4

将Dwivedi Ji的答案转换为 Kotlin。我对 Android Studio 的自动转换有一些问题。因此,花了一些时间使其工作。

现在它正在工作。如果有人需要它(在我的情况下,我正在过滤街道名称):

class StreetsAdapter( private val mContext: Context,
                      private val viewResourceId: Int,
                      private val items: ArrayList<Street>) : ArrayAdapter<Street?>(mContext, viewResourceId, items.toList()) {

    private val itemsAll = items.clone() as ArrayList<Street>
    private var suggestions = ArrayList<Street>()

    override fun getView(position: Int, convertView: View?, parent: ViewGroup): View {
        var v: View? = convertView
        if (v == null) {
            val vi = mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE) as LayoutInflater
            v = vi.inflate(viewResourceId, null)
        }
        val street: Street? = items[position]
        if (street != null) {
            val streetTitle = v?.findViewById(R.id.tvStreetTitle) as TextView?
            streetTitle?.text = street.title
        }
        return v!!
    }

    override fun getFilter(): Filter {
        return nameFilter
    }

    private var nameFilter: Filter = object : Filter() {
        override fun convertResultToString(resultValue: Any): String {
            return (resultValue as Street).title
        }

        override fun performFiltering(constraint: CharSequence?): FilterResults {
            return if (constraint != null) {
                suggestions.clear()
                for (street in itemsAll) {
                    if (street.title.toLowerCase().startsWith(constraint.toString().toLowerCase())) {
                        suggestions.add(street)
                    }
                }
                val filterResults = FilterResults()
                filterResults.values = suggestions
                filterResults.count = suggestions.size
                filterResults
            } else {
                FilterResults()
            }
        }

        override fun publishResults(constraint: CharSequence?, results: FilterResults?) {
            val filteredList =  results?.values as ArrayList<Street>?

            if (results != null && results.count > 0) {
                clear()
                for (c: Street in filteredList ?: listOf<Street>()) {
                    add(c)
                }
                notifyDataSetChanged()
            }
        }
    }
}

并设置您的适配器:

val adapter = StreetsAdapter(this,
       R.layout.item_street, //Your layout. Make sure it has [TextView] with id "tvStreetTitle" 
       arrayListOf() //Your list goes here
)
autoTextView.threshold = 1 //will start working from first character
autoTextView.setAdapter(adapter)
于 2020-04-08T10:20:29.210 回答
0

我相信最简单的方法是扩展SimpleAdapter.

public class MyAdapter extends android.widget.SimpleAdapter {

    static ArrayList<Map<String, String>> toMapList(Collection<MyObject> objectsCollection) {
        ArrayList<Map<String, String>> objectsList = new ArrayList<Map<String, String>>(objectsCollection.size());
        for (MyObject obj : objectsCollection) {
            Map<String, String> map = new HashMap<String, String>();
            map.put("name", obj.getName());
            map.put("details", obj.getDetails());
            objectsList.add(map);
        };
        return objectsList;
    }

    public MyAdapter(Context context, Collection<MyObject> objects) {

        super(context, toMapList(objects),
              R.layout.auto_complete_layout, new String[] {"name", "description"}, new int[] {R.id.name, R.id.description});
    }
}

主要缺点是这将基于名称或描述中的任何空格分隔的单词带来候选人。如果您将另一个字段添加到您的auto_complete_layout,它也将参与匹配。

因此,我完成了重写 SimpleAdapter 以更好地满足我的需求,删除了大量与我的用例无关的基类开销。但是上面的几行代码为您提供了一个良好的开端,并为开始定制提供了可靠的参考。

于 2015-03-19T09:30:07.947 回答
0

这是 AutoCompleteTextView 的扩展,Kotlin

fun AutoCompleteTextView.showListDropDown(list: List<Any?>, action:(item: Any) -> Unit){

    val adapter = ArrayAdapter<Any?>(
        this.context,
        R.layout.custom_dropdown_item,
        ArrayList<Any?>(list)
    )

    this.setAdapter(adapter)

    this.threshold = 1

    this.onItemClickListener = AdapterView.OnItemClickListener { parent, view, position, id ->
        val item = adapter.getItem(position)!!
        action(item)
    }

    this.setOnTouchListener { _: View?, _: MotionEvent? ->
        if (list.isNotEmpty()) {
            if (this.text.toString() != "") adapter.filter
                .filter(null)
            this.showDropDown()
        }
        return@setOnTouchListener true
    }
}
于 2020-11-10T17:45:09.793 回答
0

始终记住,当您为 AutoCompleteTextView 自定义 ArrayAdapter 时,您必须实现自己的过滤方法。

于 2020-01-16T07:39:23.997 回答