在Android中的ArrayList中使用过滤器的搜索框

时间:2017-09-20 01:29:44

标签: android listview arraylist searchview

我正在尝试在ArrayList中进行自动搜索,并在我的Activity中的ListView中显示它。所以我设法在适配器中生成过滤器,但是当我输入错误时我的过滤器有问题,按下后退按钮它不会继续搜索。

另外,有没有办法让searchView消失?我想从列表视图中选择一个项目后就消失了。

这是我处理SearchView的活动的一部分:

@Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_search_team, menu);

        SearchManager searchManager = (SearchManager)
                getSystemService(Context.SEARCH_SERVICE);
        MenuItem searchMenuItem = menu.findItem(R.id.search);
        SearchView searchView = (SearchView) searchMenuItem.getActionView();

        searchView.setSearchableInfo(searchManager.
                getSearchableInfo(getComponentName()));
        searchView.setSubmitButtonEnabled(true);
        searchView.setOnQueryTextListener(this);

        return true;
    }

    @Override
    public boolean onQueryTextSubmit(String query) {
        return false;
    }

    @Override
    public boolean onQueryTextChange(String newText) {

        initAdapter(newText);

        return true;
    }

    public void initAdapter(String text) {

        adapter_search = new FriendListAdapter(this,listUsers);
        listview.setVisibility(View.VISIBLE);
        listview.bringToFront();
        listview.setAdapter(adapter_search);
        adapter_search.filter(text);
    }

这是我的适配器:

public class FriendListAdapter extends BaseAdapter {

    // Declare Variables
    Context mContext;
    LayoutInflater inflater;
    private List<UserProject> worldpopulationlist = null;
    private ArrayList<UserProject> arraylist;

    public FriendListAdapter(Context context, List<UserProject> worldpopulationlist) {
        mContext = context;
        this.worldpopulationlist = worldpopulationlist;
        inflater = LayoutInflater.from(mContext);
        this.arraylist = new ArrayList<UserProject>();
        this.arraylist.addAll(worldpopulationlist);
    }

    public class ViewHolder {
        TextView rank, company;
        CircleImageView picture;
        CheckBox check;
    }

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

    @Override
    public UserProject getItem(int position) {
        return worldpopulationlist.get(position);
    }

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

    public View getView(final int position, View view, ViewGroup parent) {
        final ViewHolder holder;
        if (view == null) {
            holder = new ViewHolder();
            view = inflater.inflate(R.layout.adapter_teams, null);
            // Locate the TextViews in listview_item.xml
            holder.rank = (TextView) view.findViewById(R.id.name);
            holder.company = (TextView) view.findViewById(R.id.description);
            holder.picture = (CircleImageView) view.findViewById(R.id.profile_image);
            holder.check = (CheckBox) view.findViewById(R.id.check);
            view.setTag(holder);
        } else {
            holder = (ViewHolder) view.getTag();
        }
        // Set the results into TextViews
        holder.check.setVisibility(View.INVISIBLE);
        holder.rank.setText(worldpopulationlist.get(position).getName());
        if (worldpopulationlist.get(position).getImageURL() != null) {
                Picasso.with(mContext).load(worldpopulationlist.get(position).getImageURL()).into(holder.picture);
        }

        // Listen for ListView Item Click
        view.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View arg0) {
                // Send single item click data to SingleItemView Class
                Intent intent = new Intent(mContext, ActivityTeams.class);
                if (ActivityTeams.user_type == 1) {
                    ActivityTeams.newList.add(worldpopulationlist.get(position));
                } else if (ActivityTeams.user_type == 2) {
                    ActivityTeams.listOwners.add(worldpopulationlist.get(position));
                }

                // Pass all data rank
                //intent.putExtra("rank",(worldpopulationlist.get(position).getName()));
                // Pass all data flag
                // Start SingleItemView Class
                mContext.startActivity(intent);
                System.out.println(worldpopulationlist.get(position).getName());
                worldpopulationlist.clear();
                ActivityTeams.listview.setVisibility(View.GONE);
            }
        });

        return view;
    }

    // Filter Class
    public void filter(String charText) {
        charText = charText.toLowerCase(Locale.getDefault());
        worldpopulationlist.clear();
        if (charText.length() == 0) {
            worldpopulationlist.addAll(arraylist);
        }
        else
        {
            for (UserProject wp : arraylist)
            {
                if (wp.getName().toLowerCase(Locale.getDefault()).contains(charText))
                {
                    worldpopulationlist.add(wp);
                }
            }
        }
        notifyDataSetChanged();
    }

}

2 个答案:

答案 0 :(得分:1)

适配器:添加一个新列表来存储完整的项目

public class ExampleAdapter extends RecyclerView.Adapter<ExampleAdapter.ExampleViewHolder> implements Filterable {
private List<ExampleItem> exampleList;
private List<ExampleItem> exampleListFull;

class ExampleViewHolder extends RecyclerView.ViewHolder {
    ImageView imageView;
    TextView textView1;
    TextView textView2;

    ExampleViewHolder(View itemView) {
        super(itemView);
        imageView = itemView.findViewById(R.id.image_view);
        textView1 = itemView.findViewById(R.id.text_view1);
        textView2 = itemView.findViewById(R.id.text_view2);
    }
}

ExampleAdapter(List<ExampleItem> exampleList) {
    this.exampleList = exampleList;
    exampleListFull = new ArrayList<>(exampleList);
}

确保添加此 exampleListFull = new ArrayList<>(exampleList); 这样完整列表将与主列表分开处理。

现在将过滤器添加到您的适配器:

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

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

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

            for (ExampleItem item : exampleListFull) {
                if (item.getText2().toLowerCase().contains(filterPattern)) {
                    filteredList.add(item);
                }
            }
        }

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

        return results;
    }

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

在您的活动中,只需将文本侦听器设置到您的搜索框并调用适配器过滤器 onQueryTextChange:

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

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

就是这样! :)

答案 1 :(得分:0)

Here,

ArrayList<ChannelData> channelData = new ArrayList<>();
ArrayList<ChannelData> filtered_channelData = new ArrayList<>();   


edt_search_channel.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
            }

            @Override
            public void onTextChanged(CharSequence charSequence, int start, int before, int count) {

                if (filtered_channelData != null) {
                    filtered_channelData.clear();
                    Log.d("mytag", "list is clear" + filtered_channelData.size());
                }

                for (int i = 0; i < channelData.size(); i++) {
                    if (channelData.get(i).getName().toLowerCase().trim()
                            .contains(edt_search_channel.getText().toString().toLowerCase().trim())) {
                        filtered_channelData.add(channelData.get(i));

                        HashSet hs = new HashSet();
                        hs.addAll(filtered_channelData);
                        filtered_channelData.clear();
                        filtered_channelData.addAll(hs);
                    }
                }
                channelAdapter = new ChannelAdapter(context, filtered_channelData, dialogChannel);
                rv_channel.setAdapter(channelAdapter);
                Log.d("mytag", "filtered_skill_listing size in out of for loop" + filtered_channelData.size());
                channelAdapter.notifyDataSetChanged();
            }

            @Override
            public void afterTextChanged(Editable editable) {
                if (edt_search_channel.getText().toString().equals("")) {
                    channelAdapter = new ChannelAdapter(context, channelData, dialogChannel);
                    rv_channel.setAdapter(channelAdapter);
                    channelAdapter.notifyDataSetChanged();
                }
            }
        });