Android RecyclerView通过我的EditText搜索过滤
创始人
2024-08-15 07:00:32
0

要实现RecyclerView的搜索过滤功能,可以按照以下步骤进行操作:

  1. 在布局文件中,添加一个EditText用于输入搜索关键字:

  1. 在RecyclerView的Adapter中创建一个新的List用于保存原始数据源,以便进行搜索过滤:
private List originalList;
private List filteredList;
  1. 在Adapter的构造函数中,将原始数据源复制到originalList中,并将filteredList初始化为originalList的副本:
public MyAdapter(List itemList) {
    this.originalList = new ArrayList<>(itemList);
    this.filteredList = new ArrayList<>(itemList);
}
  1. 在Adapter中添加一个方法用于执行搜索过滤操作,该方法将根据搜索关键字更新filteredList:
public void filter(String text) {
    filteredList.clear();
    if (text.isEmpty()) {
        filteredList.addAll(originalList);
    } else {
        text = text.toLowerCase();
        for (Item item : originalList) {
            if (item.getName().toLowerCase().contains(text)) {
                filteredList.add(item);
            }
        }
    }
    notifyDataSetChanged();
}
  1. 在Activity或Fragment中,获取EditText的引用,并添加一个TextWatcher监听器,当搜索关键字发生变化时调用Adapter的filter方法:
EditText editTextSearch = findViewById(R.id.editTextSearch);
editTextSearch.addTextChangedListener(new TextWatcher() {
    @Override
    public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
        // Do nothing
    }

    @Override
    public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
        myAdapter.filter(charSequence.toString());
    }

    @Override
    public void afterTextChanged(Editable editable) {
        // Do nothing
    }
});
  1. 在Activity或Fragment中,创建RecyclerView的Adapter并设置给RecyclerView:
RecyclerView recyclerView = findViewById(R.id.recyclerView);
MyAdapter myAdapter = new MyAdapter(itemList);
recyclerView.setAdapter(myAdapter);

现在,当用户在EditText中输入搜索关键字时,RecyclerView会自动更新以显示匹配的项。

相关内容

热门资讯

让我来分享经验!xpoker辅... 让我来分享经验!xpoker辅助器(辅助挂)原来是真的有挂(的确有挂辅助攻略)1、每一步都需要思考,...
一分钟揭秘!xpoker辅助神... 一分钟揭秘!xpoker辅助神器(辅助挂)好像真的有挂(有挂辅助辅助器)1、脚本辅助下载、免费透视脚...
必看攻略!pokemmo脚本辅... 必看攻略!pokemmo脚本辅助(辅助挂)切实是真的有挂(有挂技巧辅助软件)1、完成有辅助插件,帮助...
总算了解!hhpoker买挂(... 总算了解!hhpoker买挂(辅助挂)竟然存在有挂(有挂方法辅助工具)1、实时透视辅助更新:用户可以...
今日焦点!poker辅助器免费... 今日焦点!poker辅助器免费安装(辅助挂)一直真的是有挂(有挂教程辅助攻略)1、免费脚本咨询教程、...
重大通报!模拟器打开hhpok... 重大通报!模拟器打开hhpoker(辅助挂)真是存在有挂(详细教程辅助脚本)1、点击下载安装,脚本分...
分享个大家!pokerworl... 分享个大家!pokerworld破解版下载(辅助挂)确实存在有挂(有挂方略辅助软件)1、起透看视 辅...
热点推荐!德州局hhpoker... 热点推荐!德州局hhpoker(辅助挂)原来是有挂(有挂方式辅助器)1、点击下载安装,脚本分类一目了...
玩家必看科普!hhpoker德... 玩家必看科普!hhpoker德州挂真的有吗(辅助挂)确实真的是有挂(有挂教学辅助方法)暗藏猫腻,小编...
玩家必看秘籍!wepoker黑... 玩家必看秘籍!wepoker黑侠破解(辅助挂)切实真的有挂(有挂解惑辅助方法)1、有没有辅助教程、有...