Android Listview:搜索项目后不再出现
创始人
2024-09-30 10:30:30
0

要实现在搜索项目后不再出现的功能,可以使用一个过滤器来过滤ListView中的数据,并动态更新ListView的内容。

以下是一个示例代码:

public class MainActivity extends AppCompatActivity implements SearchView.OnQueryTextListener {
    private ListView listView;
    private ArrayAdapter adapter;

    private ArrayList originalData;
    private ArrayList filteredData;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        listView = findViewById(R.id.listView);
        originalData = new ArrayList<>();
        originalData.add("Apple");
        originalData.add("Banana");
        originalData.add("Cherry");
        originalData.add("Durian");
        
        filteredData = new ArrayList<>();
        filteredData.addAll(originalData);

        adapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, filteredData);
        listView.setAdapter(adapter);

        SearchView searchView = findViewById(R.id.searchView);
        searchView.setOnQueryTextListener(this);
    }

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

    @Override
    public boolean onQueryTextChange(String newText) {
        filteredData.clear();
        if (TextUtils.isEmpty(newText)) {
            filteredData.addAll(originalData);
        } else {
            for (String item : originalData) {
                if (item.toLowerCase().contains(newText.toLowerCase())) {
                    filteredData.add(item);
                }
            }
        }
        adapter.notifyDataSetChanged();
        return true;
    }
}

上述代码中,我们首先定义了一个原始数据列表originalData,以及一个过滤后的数据列表filteredData。在onCreate方法中,我们将originalData的内容复制给filteredData,并将filteredData设置为ListView的数据源。然后,我们通过实现SearchView的OnQueryTextListener接口,监听搜索框中的文本变化。

在onQueryTextChange方法中,我们先清空filteredData列表,然后判断搜索框中的文本是否为空。如果为空,就将originalData的内容全部添加到filteredData中;如果不为空,就遍历originalData列表,判断每个项目是否包含搜索文本,如果包含就添加到filteredData中。

最后,我们调用adapter.notifyDataSetChanged()方法,通知ListView刷新数据。这样就实现了根据搜索文本过滤ListView的功能。

相关内容

热门资讯

2分钟辅助!创思维激k有挂吗,... 【亲,创思维激k有挂吗 这款游戏可以开挂的,确实是有挂的,很多玩家在这款创思维激k有挂吗中打牌都会发...
第十分钟辅助!wepoker亲... 第十分钟辅助!wepoker亲友圈有用吗,丹东约战麻将辅助器(一分钟了解开挂辅助脚本);亲真的是有正...
6分钟开挂!wepoker透视... 6分钟开挂!wepoker透视脚本下载,闲逸辅助脚本(透视透视开挂辅助神器);无需打开直接搜索微信(...
5分钟辅助!皮皮胡子辅助,潮友... 5分钟辅助!皮皮胡子辅助,潮友会虾蟹骰子概率计算方式(玩家必看开挂辅助安装);潮友会虾蟹骰子概率计算...
1分钟辅助!微信微乐有挂没有,... 1分钟辅助!微信微乐有挂没有,微信中至有辅助吗(透视有挂开挂辅助平台);相信小伙伴都知道这个微信中至...
第1分钟辅助!禅游游戏辅助,乐... 第1分钟辅助!禅游游戏辅助,乐平包王攻略(科普常识开挂辅助平台);大家肯定在之前乐平包王攻略或者乐平...
第9分钟开挂!广西微乐小程序脚... 第9分钟开挂!广西微乐小程序脚本,河洛杠次插件(最新技巧开挂辅助下载)【无需打开直接搜索加薇1367...
第4分钟辅助!贪玩互娱辅助,微... 第4分钟辅助!贪玩互娱辅助,微乐小程序挂哪里有(今日重大通报开挂辅助工具);相信小伙伴都知道这个微乐...
第七分钟开挂!欢聚水鱼天下辅助... 您好:这款欢聚水鱼天下辅助游戏是可以开挂的,确实是有挂的,很多玩家在这款欢聚水鱼天下辅助游戏中打牌都...
第四分钟辅助!xpoker透视... 第四分钟辅助!xpoker透视辅助,小闲川南手游辅助器(技巧知识分享开挂辅助安装);小薇(透视辅助)...