【问题标题】:Search an ArrayList Model搜索 ArrayList 模型
【发布时间】:2017-09-14 07:33:43
【问题描述】:

我想获取所有包含基于 itemName 的搜索输入的项目。在 c# 中,我可以使用 lambda,但我找不到任何关于 android 的参考。

这是模型类:

public class ModelItem {
    public long itemId;
    public String itemName;
    public double price;
}

这是我的清单:

public static ArrayList<ModelItem> items;

我将使用列表来获取项目。提前谢谢你。

【问题讨论】:

  • 显示完整代码。

标签: java android


【解决方案1】:

使用下面的代码

public void getAllItems(ArrayList<ModelItem> items, String searchItem) {
for(ModelItem item : items) {
 if(item.getItemName().contains(searchItem)) {
    // here you are getting item which matches inside your list
}
}

【讨论】:

  • 既然你是第一个,你能把“相等”部分增强为包含吗?
  • 当然,我的错
【解决方案2】:

嘿,我在 github 中有一个满足您要求的示例,您需要在主类中使用 QueryTextListener,然后按照示例中给出的 setFilter 到适配器 请查看此链接:https://github.com/Wrdlbrnft/Searchable-RecyclerView-Demo

【讨论】:

    【解决方案3】:

    第一步,将项目复制到tempList

    private ArrayList<ModelItem> items; // You have data into this list
    private ArrayList<ModelItem> tempData = new ArrayList<>();
    for (ModelItem item : items) {
        tempData.add(item);
    }
    

    这是根据查询过滤项目

    public void filter(String query) {
       items.clear();
       if (query.length() > 0) {
           for (ModelItem currItem : tempData) {
              // Add data into list, if item is having query string
              if (currItem.getItemName().toLowerCase().contains(query)) {
                  mData.add(currItem);
              }
           }
       } else {
           // Adding all the items, if query is empty
           for (ModelItem item : tempData) {
               items.add(item);
           }
       }
       notifyDataSetChanged(); // notify the changes, if you are using an adapter.
    }
    

    【讨论】:

      【解决方案4】:

      我认为您有一个包含项目的列表视图。现在你想用搜索字符串过滤它们。

      您必须在自定义适配器中实现 FilterableHow to filter an adapter

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2012-02-01
        • 2011-01-07
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多