从" startsWith"更改AutoCompleteTextView过滤器到"包含"?

时间:2016-01-28 14:02:21

标签: android autocompletetextview

我想更改AutoCompleteTextView中的默认过滤。默认筛选查找以给定标记开始的所有字符串。我的项目要求过滤应该找到包含给定标记的所有字符串。

有可能吗?

5 个答案:

答案 0 :(得分:16)

我找到了解决方案,感谢Google和搜索两天。正如@ torque203建议的那样,我已经实现了自己的自定义适配器。首先在适配器中为自定义项定义一个新的XML文件:

autocomplete_item.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:textAppearance="?android:attr/textAppearanceMedium"
        android:text="Medium Text"
        android:paddingLeft="8dp"
        android:paddingRight="8dp"
        android:paddingTop="16dp"
        android:paddingBottom="16dp"
        android:id="@+id/lbl_name" />
</RelativeLayout>

为您的姓名创建新课程:

姓名

public class Names {
    public String name;
}

NamesAdapter

public class NamesAdapter extends ArrayAdapter<Names> {

    Context context;
    int resource, textViewResourceId;
    List<Names> items, tempItems, suggestions;

    public NamesAdapter(Context context, int resource, int textViewResourceId, List<Names> items) {
        super(context, resource, textViewResourceId, items);
        this.context = context;
        this.resource = resource;
        this.textViewResourceId = textViewResourceId;
        this.items = items;
        tempItems = new ArrayList<Names>(items); // this makes the difference.
        suggestions = new ArrayList<Names>();
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        View view = convertView;
        if (convertView == null) {
            LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            view = inflater.inflate(R.layout.autocomplete_item, parent, false);
        }
        Names names = items.get(position);
        if (names != null) {
            TextView lblName = (TextView) view.findViewById(R.id.lbl_name);
            if (lblName != null)
                lblName.setText(names.name);
        }
        return view;
    }

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

    /**
     * Custom Filter implementation for custom suggestions we provide.
     */
    Filter nameFilter = new Filter() {
        @Override
        public CharSequence convertResultToString(Object resultValue) {
            String str = ((Names) resultValue).name;
            return str;
        }

        @Override
        protected FilterResults performFiltering(CharSequence constraint) {
            if (constraint != null) {
                suggestions.clear();
                for (Names names : tempItems) {
                    if (names.name.toLowerCase().contains(constraint.toString().toLowerCase())) {
                        suggestions.add(names);
                    }
                }
                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) {
            List<Names> filterList = (ArrayList<Names>) results.values;
            if (results != null && results.count > 0) {
                clear();
                for (Names names : filterList) {
                    add(names);
                    notifyDataSetChanged();
                }
            }
        }
    };
}

SearchActivity(或您的主要活动)

....
   List<Names> namesList =  //your names list;
   NamesAdapter namesAdapter = new NamesAdapter(
                    SearchActivity.this,
                    R.layout.activity_search,
                    R.id.lbl_name,
                    namesList
            );
            //set adapter into listStudent
            autoCompleteTextView.setAdapter(namesAdapter);
            autoCompleteTextView.showDropDown();
...

答案 1 :(得分:0)

是的,这是可能的。

第一种方式:

您应该创建一个实现ListAdapterFilterable的自定义适配器。

Filter可以实现“包含”过滤器逻辑。

并将此适配器设置为AutoCompleteTextView的适配器。

第二种方式:

如果您已使用ArrayAdapter。您可以覆盖它的getFilter()方法。

答案 2 :(得分:0)

只是为了扩展Caffe Latte的好答案:

1)不需要autoCompleteTextView.showDropDown();

2)要检索输入对象,可以使用:

//retrieve the input in the autoCompleteTextView
        autoCompleteTextView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            //parent The AdapterView where the click happened.
            //view The view within the AdapterView that was clicked (this will be a view provided by the adapter)
            //position The position of the view in the adapter
            //id The row id of the item that was clicked.
            public void onItemClick(AdapterView<?> parent, View view, int position, long rowId) {
                String selection =parent.getItemAtPosition(position).toString();
                Toast.makeText(parent.getContext(),"" + selection,Toast.LENGTH_SHORT).show();
            }
        });

从父级检索的对象必须实现toString()方法。

答案 3 :(得分:0)

//试试这个

s := fmt.Sprintf("%d-%02d-%02d %02d:%02d:%02d\n",
    t.Year(), t.Month(), t.Day(),
    t.Hour(), t.Minute(), t.Second())

£ 这对我有用

答案 4 :(得分:0)

这是@Caffe Latte发布的内容的一个简单的Kotlin版本。

您不需要自定义布局文件,只需使用默认的android.R.layout.simple_list_item_1

为该适配器提供任何类,包括纯字符串。它将仅使用toString()确定显示文本。

import android.content.Context
import android.widget.ArrayAdapter
import android.widget.Filter
import androidx.annotation.IdRes
import androidx.annotation.LayoutRes
import java.util.*

class AutoCompleteAdapter(
        context: Context,
        @LayoutRes resource: Int,
        @IdRes textViewResourceId: Int = 0,
        internal var items: List<Any> = listOf()
)
    : ArrayAdapter<Any>(context, resource, textViewResourceId, items) {


    internal var tempItems: MutableList<Any> = mutableListOf()
    internal var suggestions: MutableList<Any> = mutableListOf()

    /**
     * Custom Filter implementation for custom suggestions we provide.
     */
    private var filter: Filter = object : Filter() {

        override fun performFiltering(constraint: CharSequence?): FilterResults {
            return if (constraint != null) {
                suggestions.clear()
                tempItems.forEach {
                    if (it.toString().toLowerCase(Locale.getDefault()).contains(constraint.toString().toLowerCase(Locale.getDefault()))) {
                        suggestions.add(it)
                    }
                }

                val filterResults = FilterResults()
                filterResults.values = suggestions
                filterResults.count = suggestions.size
                filterResults
            } else {
                FilterResults()
            }
        }

        override fun publishResults(constraint: CharSequence?, results: FilterResults) {
            val filterList = results.values as? List<Any>
            if (results.count > 0) {
                clear()
                filterList?.forEach {
                    add(it)
                }.also {
                    notifyDataSetChanged()
                }
            }
        }
    }

    init {
        tempItems = items.toMutableList()
        suggestions = ArrayList()
    }

    override fun getFilter(): Filter {
        return filter
    }
}