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会自动更新以显示匹配的项。

相关内容

热门资讯

WPK安卓手册!德普之星透视辅... WPK安卓手册!德普之星透视辅助软件,德州微扑克原来有开挂方法1、德普之星透视辅助软件模拟器是什么优...
WPK透视大纲!德普之星透视辅... WPK透视大纲!德普之星透视辅助插件,德州微扑克总是是有透视软件1、德普之星透视辅助插件公共底牌简单...
WPK有透视大纲!wepoke... WPK有透视大纲!wepoker私人局外卦,德州微扑克果然是真的有辅助插件1、任何wepoker私人...
WPK辅助器烘培!wepoke... WPK辅助器烘培!wepoker透视脚本网页,德州微扑克原来存在有辅助方法1、上手简单,内置详细流程...
WPK辅助器法子!wejoke... WPK辅助器法子!wejoker手机版透视脚本,德州微扑克总是真的是有辅助插件进入游戏-大厅左侧-新...
WPK多开教程书!wepoke... WPK多开教程书!wepoker有透视底牌吗,德州微扑克好像是真的有辅助器攻略暗藏猫腻,小编详细说明...
WPK俱乐部方案!hhpoke... WPK俱乐部方案!hhpoker辅助软件下载,德州微扑克确实存在有透视技巧1、不需要AI权限,帮助你...
WPK有透视法子!we-pok... WPK有透视法子!we-poker辅助器,德州微扑克一直真的有辅助插件1、we-poker辅助器有没...
WPK官网要领!wepoker... WPK官网要领!wepoker公共底牌,德州微扑克其实是真的有透视脚本wepoker公共底牌脚本下载...
WPK俱乐部绝活!wepoke... WPK俱乐部绝活!wepoker有辅助功能吗,德州微扑克一贯是有开挂软件1、wepoker有辅助功能...