SearchView на панели инструментов не фильтрует ListFragment - PullRequest
0 голосов
/ 22 ноября 2018

Я пытаюсь реализовать SearchView в Toolbar для ListFragment, но по какой-то причине фильтрация не работает.SearchView и клавиатура отображаются как обычно, но ListView не фильтруется, когда я что-то набираю.

класс фрагмента

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);
    }
}

адаптер класса

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();
        }
    };
}

1 Ответ

0 голосов
/ 22 ноября 2018

Вам не хватает OnQueryTextListener на вашем SearchView, просто подключите его, чтобы адаптер знал, когда фильтровать:

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;
    }
});
...