工具栏中的 SearchView 未过滤 ListFragment

SearchView in Toolbar not filtering ListFragment

我正在尝试在 Toolbar 中为 ListFragment 实施 SearchView,但由于某种原因过滤不起作用。 SearchView 和键盘显示正常,但 ListView 在我输入内容时未被过滤。

片段class

public class MyFragment extends ListFragment implements SearchView.OnQueryTextListener {

    public MyFragment() {}

    private ListView lv;
    private MyListAdapter mAdapter;

    public static MyFragment newInstance() {
        return new MyFragment();
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setHasOptionsMenu(true);
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_list, container, false);
        initialize();
        return view;
    }

    List<Product> myList = new ArrayList<>();
    private void initialize() {
        String[] items = getActivity().getResources().getStringArray(R.array.product_names);
        String[] itemDescriptions = getActivity().getResources().getStringArray(R.array.product_descriptions);
        for (int n = 0; n < items.length; n++){
            Product product = new Product();
            product.setProductName(items[n]);
            product.setProductDescription(itemDescriptions[n]);
            myList.add(product);
        }

        mAdapter = new MyListAdapter(myList, getActivity());
        setListAdapter(mAdapter);
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        View v = getView();

        mTwoPane = getActivity().findViewById(R.id.detail_container) != null;

        assert v != null;
        lv = v.findViewById(android.R.id.list);
        lv.setTextFilterEnabled(true);
        lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                MyListAdapter adapter = (MyListAdapter) parent.getAdapter();
            }
        });

        super.onActivityCreated(savedInstanceState);
    }

    @Override
    public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
        MenuInflater mInflater = Objects.requireNonNull(getActivity()).getMenuInflater();
        mInflater.inflate(R.menu.menu_search, menu);

        MenuItem searchitem = menu.findItem(R.id.action_search);
        SearchView searchView = (SearchView) searchitem.getActionView();
        searchView.setQueryHint(Objects.requireNonNull(getContext()).getText(R.string.searchhint_productname));

        super.onCreateOptionsMenu(menu, inflater);
    }
}

适配器class

public class MyListAdapter extends BaseAdapter implements Filterable {

    private List<Product> myList;
    private List<Product> myListFull;
    private LayoutInflater mInflater;

    public MyListAdapter(List<Product> data, Context context) {
        myList = data;
        myList = new ArrayList(myList);
        myListFull = new ArrayList(myList);
        mInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    }

    @Override
    public int getCount() {
        return myList.size();
    }

    @Override
    public Object getItem(int position) {
        return myList.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

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

        MyListAdapter.ViewHolder holder;

        if (convertView == null) {
            convertView = mInflater.inflate(R.layout.listitem, parent, false);
            holder = new MyListAdapter.ViewHolder();

            holder.title = convertView.findViewById(R.id.listitem_title);
            holder.description = convertView.findViewById(R.id.listitem_subtitle);

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


        Product mProduct = (Product)getItem(position);
        holder.title.setText(mProduct.getProductName());
        holder.description.setText(mProduct.getProductDescription());

        return convertView;
    }


    /**
     * View holder
     */
    static class ViewHolder {
        private TextView title;
        private TextView description;
    }

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

    private Filter exampleFilter = new Filter() {
        @Override
        protected FilterResults performFiltering(CharSequence constraint) {
            List<Product> filteredList = new ArrayList<>();

            if (constraint == null || constraint.length() == 0) {
                filteredList.addAll(myListFull);
            } else {
                String filterPattern = constraint.toString().toLowerCase().trim();

                for (Product item : myListFull) {
                    if (item.getProductName().toLowerCase().contains(filterPattern)) {
                        filteredList.add(item);
                    }
                }
            }

            FilterResults results = new FilterResults();
            results.values = filteredList;

            return results;
        }

        @Override
        protected void publishResults(CharSequence constraint, FilterResults results) {
            myList.clear();
            myList.addAll((List<Product>) results.values);
            notifyDataSetChanged();
        }
    };
}

您的 SearchView 上缺少 OnQueryTextListener,只需附加一个以便适配器知道何时过滤:

searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
    @Override public boolean onQueryTextSubmit(String query) {
        return false;
    }

    @Override public boolean onQueryTextChange(String newText) {
        mAdapter.getFilter().filter(newText);
        return true;
    }
});