2

我有一个 listView 和一个搜索字段,它调用我的 Adapter 的 getFilter().filter(keyword) 函数。它工作得非常好,但我想添加另一个过滤器,用于搜索我的 listViews 对象的不同标签。

所以我的适配器需要两个过滤器,最好的解决方案是什么?

谢谢,

4

3 回答 3

5

我想你自己实现了过滤器。由于您无法获得两个过滤器,因此您可以在过滤器中有一个字段来定义应该应用哪种过滤器(您可以在过滤器中使用多个过滤器)。

在使用过滤器之前,将过滤器的字段设置为所需的值。

或者:

使用关键字选择要应用的过滤器。在关键字的开头添加一些定义要应用的过滤器的字符。您可以检查必须应用String.beginsWith()哪种类型的过滤。这必须在过滤器本身中完成。getFilter.filter(keyword) 的调用者必须知道必须在字符串前面添加哪些字符。

于 2012-07-27T16:55:02.100 回答
0

在 Listview 中应用多重过滤器,并在 ListView 中使用多重排序,试试这个链接:

https://github.com/apurv3039/filter_listview/tree/master

于 2016-10-03T12:23:23.337 回答
0

我有类似的需求,我已经为自己写了。过滤器与 AND 运算符结合使用。尽可能简单。没有声称它是完美的,但它对我有用。您可以根据需要进行更改。

项目模型

public class ItemModel {

    public int ID;
    public int rating;
    public float avg;
    public String name;
    public String shortDesc;
    public boolean read;
}

和 parser.java

/**
 * This class is designed to be simple for parsing a filter of the form
 *             "object field name: variable type: operator: value"
 *
 * "ID:int:>:20";"name:string:=:20"
 * Where ';' means AND, however this is not parsed here.
 * If you need different logic, use the results.O
 *
 * Multiple filters seperated by ';'
 */
public class Parser {

    private static final String TAG = "Parser";


    public static boolean isPassingTheFiler(String filter, String field, String val) {

        String[] mGroups = parseMainGroups(filter);

        for (String mGroup : mGroups) {

            Log.e(TAG,"Working on the main Group " +mGroup );

            String[] subCommand = parseSubCommand(mGroup);

            if ( field.equals(subCommand[0])) {
                if (!processCommand(subCommand, val)) {
                    return false;
                }
            }
        }

        return true;
    }

    /**
     * parses that data assuming they are all sperated by `;`
     */
    public static String[] parseMainGroups(CharSequence commands) {

        String buffer = commands.toString();

        String parts[] = buffer.split(";");

        return parts;
    }

    public static String[] parseSubCommand(String subCommand) {

        //remove the double quotes.
        String buffer = removeDoubleQuotes(subCommand.toString());

        String parts[] = buffer.split(":");

        return parts;
    }

    public static String removeDoubleQuotes(String quotedString) {

        if ((quotedString.charAt(0) == '\"') && (quotedString.charAt(quotedString.length() - 1) == '\"')) {
            return quotedString.substring(1, quotedString.length() - 1);
        } else {
            Log.e(TAG, quotedString + " doesn't contained in double quotes!\nReturned empty string!!!");
            return "";
        }
    }

    public static boolean processCommand(String[] subCommand, String val) {

        switch (subCommand[1]) {

            case "int":
                Log.e("TAG","\tint Filer");
                return intStatement(subCommand, val);
            case "float":
                Log.e("TAG","\tfloat Filer");
                return floatStatement(subCommand, val);
            case "string":
                Log.e("TAG","\tString Filer");
                return stringStatement(subCommand, val);

            default:
                return false;
        }
    }

    /**
     * Evaluate the Int statement's correctness with the given INT value
     */
    public static boolean intStatement(String[] subCommand, String cVal) {

        String operString = subCommand[2];

        int iVal;
        int val;

        try {
            iVal = Integer.parseInt(subCommand[3]);
            val = Integer.parseInt(cVal);
        } catch (NumberFormatException e) {
            return false;
        }

        switch (operString) {

            case "=":
                return val == iVal;
            case "<":
                return val < iVal;
            case ">":
                return val > iVal;
            case "<=":
                return val <= iVal;
            case ">=":
                return val >= iVal;
            case "!=":
                return val != iVal;
            case "s" :
                //digit search as string. We look into string from that we already have
                return cVal.contains(subCommand[3]);

            default:
                Log.e("Parser", "invalid Integer Operation");

                return false;
        }
    }


    public static boolean floatStatement(String[] subCommand, String cVal) {

        String operString = subCommand[2];
        float iVal;
        float val;

        try {
            iVal = Float.parseFloat(subCommand[3]);
            val = Float.parseFloat(cVal);

        } catch (NumberFormatException e) {
            return false;
        }

        switch (operString) {

            case "=":
                return val == iVal;
            case "<":
                return val < iVal;
            case ">":
                return val > iVal;
            case "<=":
                return val <= iVal;
            case ">=":
                return val >= iVal;
            case "!=":
                return val != iVal;
            case "s" :
                //digit search as string. We look into string from that we already have
                return cVal.contains(subCommand[3]);

            default:

                Log.e("Parser", "invalid Integer Operation");

                return false;
        }
    }

    public static boolean stringStatement(String[] subCommand, String val) {

        String operString = subCommand[2];

        switch (operString) {

            case "=":
                //equality
                return val.equals(subCommand[3]);
            case "<":
                //substring
                return val.contains(subCommand[3]);
            case "sw":
                //prefix
                return val.startsWith(subCommand[3]);
            case "ew":
                //postfix
                return val.endsWith(subCommand[3]);

            default:

                Log.e("Parser", "invalid Integer Operation");

                return false;
        }
    }
}

适配器中的私有过滤器类。

    private class ItemFilter extends Filter {

        @Override
        protected FilterResults performFiltering(CharSequence constraint) {
            String charString = constraint.toString();
            String[] parts;

            FilterResults filterResults = new FilterResults();

            if (charString.isEmpty()) {
                filterResults.values = new ArrayList<>(itemList);
            } else {
                //Parse the main group
                parts = parseMainGroups(charString);

                if (parts.length < 1) {
                    filterResults.values =  new ArrayList<>(itemList);

                } else {

                    List<ItemModel> filteredList = new ArrayList<>();

                    for (ItemModel row : itemList) {

                        if ( !isPassingTheFiler(charString,"ID",""+row.ID)) {
                            continue;
                        } else {
                            Log.e("Filter", "passed on ID" + row.ID);
                        }
                        if ( !isPassingTheFiler(charString,"name",""+row.name)) {
                            continue;
                        } else {
                            Log.e("Filter", "passed on name" + row.name);
                        }
                        // passed every test asked. If empty they returned true!
                        filteredList.add(row);
                    }

                    filterResults.values = new ArrayList<>(filteredList);
                }
            }

            return filterResults;
        }

        @Override
        protected void publishResults(CharSequence constraint, FilterResults results) {

            updateList((List<ItemModel>) results.values);

        }
    }

以及适配器的 updateList 成员函数

    public void updateList(List<ItemModel> newList) {
        DiffUtil.DiffResult diffResult = DiffUtil.calculateDiff(new ItemDiffUtilCallback(newList, itemListFiltered));

        itemListFiltered.clear();
        itemListFiltered.addAll(newList);
        diffResult.dispatchUpdatesTo(this);

        Log.e("TAG", "updated with dispatch");
    }

以及有助于制作好动画的 diffutils

public class ItemDiffUtilCallback extends DiffUtil.Callback {

    private List<ItemModel> oldList;
    private List<ItemModel> newList;

    public ItemDiffUtilCallback(List<ItemModel> newList, List<ItemModel> oldList) {
        this.newList = newList;
        this.oldList = oldList;
    }

    @Override
    public int getOldListSize() {
        return oldList.size();
    }

    @Override
    public int getNewListSize() {
        return newList.size();
    }

    @Override
    public boolean areItemsTheSame(int oldItemPosition, int newItemPosition) {
        return oldList.get(oldItemPosition).ID == newList.get(newItemPosition).ID;
    }

    @Override
    public boolean areContentsTheSame(int oldItemPosition, int newItemPosition) {

         return oldList.get(oldItemPosition).equals(newList.get(newItemPosition));
    }


    @Override
    public Object getChangePayload(int oldItemPosition, int newItemPosition) {
        return super.getChangePayload(oldItemPosition, newItemPosition);
    }
于 2020-01-30T21:02:17.630 回答