19

我需要覆盖getFilter()类中的一个方法,我在 github 中ArrayAdapter 找到了源代码

//package name

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import android.content.Context;
import android.util.Log;
import android.widget.ArrayAdapter;
import android.widget.Filter;
import android.widget.Filterable;

public class CustomAdapter<T> extends ArrayAdapter<T> implements Filterable{

    private ArrayList<T> mOriginalValues;
    private List<T> mObjects;
    private CustomFilter mFilter;
    private final Object mLock = new Object();
    public CustomAdapter(Context context, int textViewResourceId, T[] objects) {
        super(context, textViewResourceId, objects);

        mObjects = Arrays.asList(objects);
        // TODO Auto-generated constructor stub
    }

    @Override
    public Filter getFilter() {
        // TODO Auto-generated method stub
        if (mFilter == null) {
            mFilter = new CustomFilter();
        }
        return mFilter;
    }


    private class CustomFilter extends Filter {
        @Override
        protected FilterResults performFiltering(CharSequence prefix) {
            FilterResults results = new FilterResults();
            Log.d("bajji", "its ---> " + prefix);
            if (mOriginalValues == null) {
                synchronized (mLock) {
                    mOriginalValues = new ArrayList<T>(mObjects);
                }
            }

            if (prefix == null || prefix.length() == 0) {
                ArrayList<T> list;
                synchronized (mLock) {
                    list = new ArrayList<T>(mOriginalValues);
                }
                results.values = list;
                results.count = list.size();
            } else {
                String prefixString = prefix.toString().toLowerCase();

                ArrayList<T> values;
                synchronized (mLock) {
                    values = new ArrayList<T>(mOriginalValues);
                }

                final int count = values.size();
                final ArrayList<T> newValues = new ArrayList<T>();
                final ArrayList<T> approxValues = new ArrayList<T>();
                final ArrayList<T> secondApproxValues = new ArrayList<T>();


                for (int i = 0; i < count; i++) {
                    final T value = values.get(i);
                    final String valueText = value.toString().toLowerCase();
                    boolean flag = true;
                    // First match against the whole, non-splitted value
                    if (valueText.startsWith(prefixString)) {
                        newValues.add(value);
                        flag = false;
                    } else {
                        final String[] words = valueText.split(" ");
                        final int wordCount = words.length;

                        // Start at index 0, in case valueText starts with space(s)
                        for (int k = 0; k < wordCount; k++) {
                            if (words[k].startsWith(prefixString)) {
                                newValues.add(value);
                                flag = false;
                                break;
                            } 
                        }
                    }

                    if(flag) {
                        if(approxMatch(valueText, prefixString) <= 3) { //change the stuff and do a levi work
                            approxValues.add(value);
                        }
                        else {
                            final String[] words = valueText.split(" ");
                            final int wordCount = words.length;

                            // Start at index 0, in case valueText starts with space(s)
                            for (int k = 0; k < wordCount; k++) {
                                if(approxMatch(words[k], prefixString) <= 3) {
                                    //leve work
                                    secondApproxValues.add(value);
                                    break;
                                }
                            }
                        }
                    }
                }
                newValues.addAll(approxValues);
                newValues.addAll(secondApproxValues);
                results.values = newValues;
                results.count = newValues.size();
            }
            return results;
        }
        @Override
        protected void publishResults(CharSequence constraint, FilterResults results) {
            //noinspection unchecked
            mObjects = (List<T>) results.values;
            if (results.count > 0) {
                notifyDataSetChanged();
            } else {
                notifyDataSetInvalidated();
            }
        }
    }

    private int approxMatch (String s, String t) {
          // an approxmimate string matching algo
          return p;
    }
}

问题是 getFilter 方法有一个私有内部类的对象,ArrayFilter它有一个方法peformFiltering,我需要在那里放一个不同的代码,所以我必须覆盖这个类。我在方法中遇到了一个异常。

在扩展 ArrayAdapter 的派生类中,我创建了一个类似于ArrayFilter并调用它的私有内部类,MyFilter我在方法中再次得到相同的异常performFiltering

我找到了解决我的问题的解决方案。我复制了ArrayAdapter类中的所有代码并创建了一个名为的新类MyAdapter,并在内部类中更改了一些代码ArrayFilter,应用程序按照我想要的方式运行。但我觉得它不是最好的解决方案。

Android 有各种 api 级别,所以如果数组适配器在不同的 api 级别更改,那么我必须在我的代码中添加这些更改。所以我觉得最好的方法是扩展类ArrayAdapter来创建MyAdapter而不是仅仅复制和粘贴代码ArrayAdapter

我如何覆盖父类的内部私有类..?

编辑:我得到的例外.. 例外

Edit2:现在我在问题中添加了完整的代码。如果我复制和编辑数组适配器,它就可以完美地工作..问题只是当我扩展时..!!现在代码和搜索工作正常。我用Log.i.. 检查了它,但 UI 中自动完成建议的下拉列表不起作用.. 我只得到我输入的第一个字符,下一个字符过滤发生,但 UI 更新没有发生。

4

4 回答 4

11

在stackoverflow社区的一些帮助之后,我删除了异常,后来我发现返回的建议并没有真正改变,因为它mObjects是从超类或基类返回的。问题是有两个公共方法getCount()getItem(int position)它们从基类中获取计数并从 mObjects 中获取列表。所以我只需要在我的课堂上添加这两种方法..

public int getCount() {
    return mObjects.size();
}

public T getItem(int position) {
    return mObjects.get(position);
}

现在mObjects将返回派生类。在 UI 的下拉列表中更新了哪些内容。

我不是Java专家,但这解决了我的问题。如果您有任何改进代码的建议,请在评论中添加或随时编辑答案。!

于 2012-05-08T04:30:52.033 回答
7

更新:

您应该覆盖类中的toString()方法T并返回过滤条件字符串。

例如,

class T {

    String firstName;
    String lastName;
    ...
    ...
    @override
    String toString() {
        return firstName + lastName;
    }
}

默认情况下,类的toString()实现Object返回getClass().getName() + '@' + Integer.toHexString(hashCode())

原来的:

数组列表引用应传递给ArrayAdapter构造函数。我认为您没有这样做,因此它无法获得过滤列表。

在此示例代码objects中,数组引用被传递给超级构造函数。

public CustomAdapter(Context context, int tvResId, ArrayList<String> objects) {
    super(context, textViewResourceId, objects);
    this.objects = objects;
}

如果您的过滤基于列表项中的简单字符串,那么您可以TextWatcher按照@Iiorry 的建议实施。但如果过滤比这复杂一点,那么你也需要实现Filterable

于 2012-05-04T06:13:06.330 回答
3

您不需要实现自己的过滤器......只需按照@Waqas 的建议覆盖 getFilter 。

这就是我所做的并且它有效。随意调整它以适应您的需求...

希望它会有所帮助。

EditText(搜索文件):

searchFilter.addTextChangedListener(mOnSearchBoxTextChanged);
private TextWatcher mOnSearchBoxTextChanged = new TextWatcher() {

        public void afterTextChanged(Editable s) {
        }

        public void beforeTextChanged(CharSequence s, int start, int count,
                int after) {
        }

        public void onTextChanged(CharSequence s, int start, int before,
                int count) {
            mAdapter.getFilter().filter(s.toString());
        }

    };

适配器 getFilter():

    class MyAdapter extends BaseAdapter implements Filterable {

            //the rest of the adapter....

            @Override
            public Filter getFilter() {
                if (newFilter == null) {
                    newFilter = new Filter() {
                        @Override
                        protected void publishResults(CharSequence prefix,
                                FilterResults results) {

                            CLog.logD( "Friends list filtered");

                            mAdapter.notifyDataSetChanged();
                        }

                        @Override
                protected FilterResults performFiltering(CharSequence constraint) {
                    constraint = constraint.toString().toLowerCase();

                    filteredFriendList = new ArrayList<FriendsListItemView>();

                    if (constraint!= null && constraint.toString().length() > 0) {
                        for (int i = 0; i < friendsList.size(); i++) {
                            FriendsListItemView newFriend = friendsList.get(i);
                            String name = newFriend.userName.getText().toString();

                            if (name.toLowerCase().contains(constraint)) {
                                filteredFriendList.add(newFriend);
                            } 
                        }

                    } else {
                        if (filteredFriendList.size() == 0) {
                            filteredFriendList = friendsList;
                        }
                    }

                    FilterResults newFilterResults = new FilterResults();
                    newFilterResults.count = filteredFriendList.size();
                    newFilterResults.values = filteredFriendList;
                    return newFilterResults;
                }
            };
                }
                return newFilter;
            }
        }
于 2012-05-03T13:35:03.187 回答
1

也许这可以帮助你:

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import android.content.Context;
import android.util.Log;
import android.widget.ArrayAdapter;
import android.widget.Filter;

public class CustomAdapter<T> extends ArrayAdapter<T> {

    private final ArrayList<T> mOriginalValues;
    private List<T> mObjects;
    private CustomFilter mFilter;
    private final Object mLock = new Object();
    public CustomAdapter(Context context, int textViewResourceId, T[] objects) {
        super(context, textViewResourceId, objects);

        mObjects = Arrays.asList(objects);
        mOriginalValues = (ArrayList<T>) Arrays.asList(objects);
        // TODO Auto-generated constructor stub
    }

    @Override
    public Filter getFilter() {
        // TODO Auto-generated method stub
        if (mFilter == null) {
            mFilter = new CustomFilter();
        }
        return mFilter;
    }


    private class CustomFilter extends Filter {
        @Override
        protected FilterResults performFiltering(CharSequence prefix) {
            FilterResults results = new FilterResults();
            Log.d("bajji", "its ---> " + prefix);

            if (prefix == null || prefix.toString().trim().length() == 0) {
                ArrayList<T> list;
                synchronized (mLock) {
                    list = new ArrayList<T>(mOriginalValues);
                }
                results.values = list;
                results.count = list.size();
            } else {
                String prefixString = prefix.toString().toLowerCase();

                ArrayList<T> values;
                synchronized (mLock) {
                    values = new ArrayList<T>(mOriginalValues);
                }

                final int count = values.size();
                final ArrayList<T> newValues = new ArrayList<T>();
                final ArrayList<T> approxValues = new ArrayList<T>();
                final ArrayList<T> secondApproxValues = new ArrayList<T>();


                for (int i = 0; i < count; i++) {
                    final T value = values.get(i);
                    final String valueText = value.toString().toLowerCase();
                    boolean flag = true;
                    // First match against the whole, non-splitted value
                    if (valueText.startsWith(prefixString)) {
                        newValues.add(value);
                        flag = false;
                    } else {
                        final String[] words = valueText.split(" ");
                        final int wordCount = words.length;

                        // Start at index 0, in case valueText starts with space(s)
                        for (int k = 0; k < wordCount; k++) {
                            if (words[k].startsWith(prefixString)) {
                                newValues.add(value);
                                flag = false;
                                break;
                            } 
                        }
                    }

                    if(flag) {
                        if(approxMatch(valueText, prefixString) <= 3) { //change the stuff and do a levi work
                            approxValues.add(value);
                        }
                        else {
                            final String[] words = valueText.split(" ");
                            final int wordCount = words.length;

                            // Start at index 0, in case valueText starts with space(s)
                            for (int k = 0; k < wordCount; k++) {
                                if(approxMatch(words[k], prefixString) <= 3) {
                                    //leve work
                                    secondApproxValues.add(value);
                                    break;
                                }
                            }
                        }
                    }
                }
                newValues.addAll(approxValues);
                newValues.addAll(secondApproxValues);
                results.values = newValues;
                results.count = newValues.size();
            }
            return results;
        }
        @Override
        protected void publishResults(CharSequence constraint, FilterResults results) {
            //noinspection unchecked
            mObjects = (List<T>) results.values;
            notifyDataSetChanged();
            clear();
            for(T tmp : mObjects){
                add(tmp);
            }

            notifyDataSetChanged();
        }
    }

    private int approxMatch (String s, String t) {
          // an approxmimate string matching algo
          return p;
    }
}

现在在getView适配器的方法中,您需要参考mObjects对象来获取 ListView 的最新可用值

于 2012-05-07T08:57:41.720 回答