ListView中的自定义过滤ArrayAdapter

发布于 2024-11-17 11:28:13 字数 7150 浏览 3 评论 0原文

我是 Android 的初学者,但我尝试制作自定义列表视图过滤,并且它以某种方式工作。我遇到的唯一问题是,我保留所有值(“原始”ArrayList)的 ArrayList 在每次过滤中的项目越来越少。我无法解释这一点,但我想你可以以某种方式帮助我。

无论如何,这里是自定义ArrayAdaptor:

public class PkmnAdapter extends ArrayAdapter<Pkmn> {

private ArrayList<Pkmn> original;
private ArrayList<Pkmn> fitems;
private Filter filter;

public PkmnAdapter(Context context, int textViewResourceId, ArrayList<Pkmn> items) {
        super(context, textViewResourceId, items);
        this.original = items;//new ArrayList<Pkmn>();
        this.fitems = items;//new ArrayList<Pkmn>();
}

@Override
public void add(Pkmn item){
    original.add(item);
}

@Override
public View getView(int position, View convertView, ViewGroup parent) {
        View v = convertView;
        if (v == null) {
            LayoutInflater vi = (LayoutInflater)getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            v = vi.inflate(R.layout.row, null);
        }
        Pkmn pkmn = original.get(position);
        if (pkmn != null) {
                TextView tt = (TextView) v.findViewById(R.id.RlabPName);
                TextView dex = (TextView)v.findViewById(R.id.RlabDex);
                ImageView img = (ImageView)v.findViewById(R.id.RimgPkmn);

                if (tt != null) { tt.setText(pkmn.getName()); }
                if (dex != null){ dex.setText(CalcDex(pkmn.getId())); }
                if (img != null){
                    int resId = getContext().getResources().getIdentifier("dex" + pkmn.getId(), "drawable", "com.compileguy.pokebwteam");
                    img.setImageResource(resId);
                }
        }
        return v;
}

@Override
public Filter getFilter()
{
    if (filter == null)
        filter = new PkmnNameFilter();

    return filter;
}

private class PkmnNameFilter extends Filter
{
        @Override
        protected FilterResults performFiltering(CharSequence constraint)
        {   
            FilterResults results = new FilterResults();
            String prefix = constraint.toString().toLowerCase();

            if (prefix == null || prefix.length() == 0)
            {
                ArrayList<Pkmn> list = new ArrayList<Pkmn>(original);
                results.values = list;
                results.count = list.size();
            }
            else
            {
                final ArrayList<Pkmn> list = original;

                int count = list.size();
                final ArrayList<Pkmn> nlist = new ArrayList<Pkmn>(count);

                for (int i=0; i<count; i++)
                {
                    final Pkmn pkmn = list.get(i);
                    final String value = pkmn.getName().toLowerCase();

                    if (value.startsWith(prefix))
                    {
                        nlist.add(pkmn);
                    }
                }
                results.values = nlist;
                results.count = nlist.size();
            }
            return results;
        }

        @SuppressWarnings("unchecked")
        @Override
        protected void publishResults(CharSequence constraint, FilterResults results) {
            fitems = (ArrayList<Pkmn>)results.values;
            clear();
            int count = fitems.size();
            for (int i=0; i<count; i++)
            {
                Pkmn pkmn = (Pkmn)fitems.get(i);
                add(pkmn);
            }

            if (fitems.size() > 0)
                notifyDataSetChanged();
            else
                notifyDataSetInvalidated();
        }

    }


private String CalcDex(int id){
    String s = String.valueOf(id);
    if (s.length() == 1)
        s = "00"+s;
    else if (s.length() == 2)
        s = "0"+s;
    return '#'+s;
}

}

注意:列表视图正确显示了项目,但是例如当我删除编辑框中的一个字母(这会触发过滤)时,这就是问题开始的地方。

--- 编辑 ---

@Janusz:非常感谢您的回答。这解决了我的问题。

这是适合我的源代码,所以如果有人遇到同样的问题,他们可以尝试这个:

private ArrayList<Pkmn> original;
private ArrayList<Pkmn> fitems;
private Filter filter;

public PkmnAdapter(Context context, int textViewResourceId, ArrayList<Pkmn> items) {
        super(context, textViewResourceId, items);
        this.original = new ArrayList<Pkmn>(items);
        this.fitems = new ArrayList<Pkmn>(items);
}

@Override
public View getView(int position, View convertView, ViewGroup parent) {
        View v = convertView;
        if (v == null) {
            LayoutInflater vi = (LayoutInflater)getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            v = vi.inflate(R.layout.row, null);
        }
        Pkmn pkmn = fitems.get(position);
        if (pkmn != null) {
                TextView tt = (TextView) v.findViewById(R.id.RlabPName);
                TextView dex = (TextView)v.findViewById(R.id.RlabDex);
                ImageView img = (ImageView)v.findViewById(R.id.RimgPkmn);

                if (tt != null) { tt.setText(pkmn.getName()); }
                if (dex != null){ dex.setText(CalcDex(pkmn.getId())); }
                if (img != null){
                    int resId = getContext().getResources().getIdentifier("dex" + pkmn.getId(), "drawable", "com.compileguy.pokebwteam");
                    img.setImageResource(resId);
                }
        }
        return v;
}

@Override
public Filter getFilter()
{
    if (filter == null)
        filter = new PkmnNameFilter();

    return filter;
}

private class PkmnNameFilter extends Filter
{
        @Override
        protected FilterResults performFiltering(CharSequence constraint)
        {   
            FilterResults results = new FilterResults();
            String prefix = constraint.toString().toLowerCase();

            if (prefix == null || prefix.length() == 0)
            {
                ArrayList<Pkmn> list = new ArrayList<Pkmn>(original);
                results.values = list;
                results.count = list.size();
            }
            else
            {
                final ArrayList<Pkmn> list = new ArrayList<Pkmn>(original);
                final ArrayList<Pkmn> nlist = new ArrayList<Pkmn>();
                int count = list.size();

                for (int i=0; i<count; i++)
                {
                    final Pkmn pkmn = list.get(i);
                    final String value = pkmn.getName().toLowerCase();

                    if (value.startsWith(prefix))
                    {
                        nlist.add(pkmn);
                    }
                }
                results.values = nlist;
                results.count = nlist.size();
            }
            return results;
        }

        @SuppressWarnings("unchecked")
        @Override
        protected void publishResults(CharSequence constraint, FilterResults results) {
            fitems = (ArrayList<Pkmn>)results.values;

            clear();
            int count = fitems.size();
            for (int i=0; i<count; i++)
            {
                Pkmn pkmn = (Pkmn)fitems.get(i);
                add(pkmn);
            }
        }

    }
}

I am a begginer in Android but I tried to make a custom listview filtering and I it worked somehow. The only problem I have is that the ArrayList that I kept all the values ( "original" ArrayList ) , is getting lower and lower on items in every filtering. I can't explain this but I thought that you can help me somehow .

Anyway here is the Custom ArrayAdaptor :

public class PkmnAdapter extends ArrayAdapter<Pkmn> {

private ArrayList<Pkmn> original;
private ArrayList<Pkmn> fitems;
private Filter filter;

public PkmnAdapter(Context context, int textViewResourceId, ArrayList<Pkmn> items) {
        super(context, textViewResourceId, items);
        this.original = items;//new ArrayList<Pkmn>();
        this.fitems = items;//new ArrayList<Pkmn>();
}

@Override
public void add(Pkmn item){
    original.add(item);
}

@Override
public View getView(int position, View convertView, ViewGroup parent) {
        View v = convertView;
        if (v == null) {
            LayoutInflater vi = (LayoutInflater)getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            v = vi.inflate(R.layout.row, null);
        }
        Pkmn pkmn = original.get(position);
        if (pkmn != null) {
                TextView tt = (TextView) v.findViewById(R.id.RlabPName);
                TextView dex = (TextView)v.findViewById(R.id.RlabDex);
                ImageView img = (ImageView)v.findViewById(R.id.RimgPkmn);

                if (tt != null) { tt.setText(pkmn.getName()); }
                if (dex != null){ dex.setText(CalcDex(pkmn.getId())); }
                if (img != null){
                    int resId = getContext().getResources().getIdentifier("dex" + pkmn.getId(), "drawable", "com.compileguy.pokebwteam");
                    img.setImageResource(resId);
                }
        }
        return v;
}

@Override
public Filter getFilter()
{
    if (filter == null)
        filter = new PkmnNameFilter();

    return filter;
}

private class PkmnNameFilter extends Filter
{
        @Override
        protected FilterResults performFiltering(CharSequence constraint)
        {   
            FilterResults results = new FilterResults();
            String prefix = constraint.toString().toLowerCase();

            if (prefix == null || prefix.length() == 0)
            {
                ArrayList<Pkmn> list = new ArrayList<Pkmn>(original);
                results.values = list;
                results.count = list.size();
            }
            else
            {
                final ArrayList<Pkmn> list = original;

                int count = list.size();
                final ArrayList<Pkmn> nlist = new ArrayList<Pkmn>(count);

                for (int i=0; i<count; i++)
                {
                    final Pkmn pkmn = list.get(i);
                    final String value = pkmn.getName().toLowerCase();

                    if (value.startsWith(prefix))
                    {
                        nlist.add(pkmn);
                    }
                }
                results.values = nlist;
                results.count = nlist.size();
            }
            return results;
        }

        @SuppressWarnings("unchecked")
        @Override
        protected void publishResults(CharSequence constraint, FilterResults results) {
            fitems = (ArrayList<Pkmn>)results.values;
            clear();
            int count = fitems.size();
            for (int i=0; i<count; i++)
            {
                Pkmn pkmn = (Pkmn)fitems.get(i);
                add(pkmn);
            }

            if (fitems.size() > 0)
                notifyDataSetChanged();
            else
                notifyDataSetInvalidated();
        }

    }


private String CalcDex(int id){
    String s = String.valueOf(id);
    if (s.length() == 1)
        s = "00"+s;
    else if (s.length() == 2)
        s = "0"+s;
    return '#'+s;
}

}

NOTE: The listview is showing correctly the items but when for exaple I remove a letter in the editbox ( which triggers the filtering ) this is where the problems start.

--- EDIT ---

@Janusz: Many thanks for your answer . That solved my problem .

Here is the source code that works for me , so if anyone has the same issue they could try this one :

private ArrayList<Pkmn> original;
private ArrayList<Pkmn> fitems;
private Filter filter;

public PkmnAdapter(Context context, int textViewResourceId, ArrayList<Pkmn> items) {
        super(context, textViewResourceId, items);
        this.original = new ArrayList<Pkmn>(items);
        this.fitems = new ArrayList<Pkmn>(items);
}

@Override
public View getView(int position, View convertView, ViewGroup parent) {
        View v = convertView;
        if (v == null) {
            LayoutInflater vi = (LayoutInflater)getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            v = vi.inflate(R.layout.row, null);
        }
        Pkmn pkmn = fitems.get(position);
        if (pkmn != null) {
                TextView tt = (TextView) v.findViewById(R.id.RlabPName);
                TextView dex = (TextView)v.findViewById(R.id.RlabDex);
                ImageView img = (ImageView)v.findViewById(R.id.RimgPkmn);

                if (tt != null) { tt.setText(pkmn.getName()); }
                if (dex != null){ dex.setText(CalcDex(pkmn.getId())); }
                if (img != null){
                    int resId = getContext().getResources().getIdentifier("dex" + pkmn.getId(), "drawable", "com.compileguy.pokebwteam");
                    img.setImageResource(resId);
                }
        }
        return v;
}

@Override
public Filter getFilter()
{
    if (filter == null)
        filter = new PkmnNameFilter();

    return filter;
}

private class PkmnNameFilter extends Filter
{
        @Override
        protected FilterResults performFiltering(CharSequence constraint)
        {   
            FilterResults results = new FilterResults();
            String prefix = constraint.toString().toLowerCase();

            if (prefix == null || prefix.length() == 0)
            {
                ArrayList<Pkmn> list = new ArrayList<Pkmn>(original);
                results.values = list;
                results.count = list.size();
            }
            else
            {
                final ArrayList<Pkmn> list = new ArrayList<Pkmn>(original);
                final ArrayList<Pkmn> nlist = new ArrayList<Pkmn>();
                int count = list.size();

                for (int i=0; i<count; i++)
                {
                    final Pkmn pkmn = list.get(i);
                    final String value = pkmn.getName().toLowerCase();

                    if (value.startsWith(prefix))
                    {
                        nlist.add(pkmn);
                    }
                }
                results.values = nlist;
                results.count = nlist.size();
            }
            return results;
        }

        @SuppressWarnings("unchecked")
        @Override
        protected void publishResults(CharSequence constraint, FilterResults results) {
            fitems = (ArrayList<Pkmn>)results.values;

            clear();
            int count = fitems.size();
            for (int i=0; i<count; i++)
            {
                Pkmn pkmn = (Pkmn)fitems.get(i);
                add(pkmn);
            }
        }

    }
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

吃素的狼 2024-11-24 11:28:13

您的问题是这样的:

this.original = items;
this.fitems = items;

Items 是您用于 ListView 的列表,将其放入两个不同的变量中不会产生两个不同的列表。您只是为列表项指定了两个不同的名称。

您可以使用:

this.fitems = new ArrayList(items);

这应该生成一个新列表,并且此列表上的更改只会更改 fitem 列表。

Your problem are this lines:

this.original = items;
this.fitems = items;

Items is the list you use for your ListView and putting it in two different variables does not make two different lists out of it. You are only giving the list items two different names.

You can use:

this.fitems = new ArrayList(items);

that should generate a new List and changes on this list will only change the fitems list.

您可以通过在 Pkmn 类上创建一个 toString() 方法来实现相同的效果,该方法返回您想要过滤的值。

you can accomplish the same effect by just creating a toString() method on your Pkmn class that returns the value you want to filter by.

↙厌世 2024-11-24 11:28:13

我发现过滤 ArrayAdapter 的最佳方法是创建自己的过滤器类:

private class MyFilter extends Filter

然后在该函数中创建新的对象数组以在过滤器之后显示(您可以在 class ArrayAdapter)

@Override
protected FilterResults performFiltering(CharSequence prefix)

现在,技巧就在这个方法中

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

,当您使用数组适配器时,您不能执行此操作:

myAdapterData = results.values

从那时起,您将数据与超级数据断开连接,您必须执行此操作以保留对超级原始数据数组:

data.clear();
data.addAll((List<YourType>) results.values);

然后覆盖

getFilter()

,例如:

@Override
public Filter getFilter() {
    if (filter == null) {
        filter = new MyFilter();
    }
    return filter;
}

The best way I found to to filter ArrayAdapter is to create my own filter class:

private class MyFilter extends Filter

then in that function create the new object array to display after the filter (you can find good implementation in the source code of class ArrayAdapter)

@Override
protected FilterResults performFiltering(CharSequence prefix)

now the trick is in this method

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

when you use the Array adapter you can't do this:

myAdapterData = results.values

since then you disconnect your data from the super data, you must do this to keep your reference to the super original data array:

data.clear();
data.addAll((List<YourType>) results.values);

and then override

getFilter()

in your adapter, for example:

@Override
public Filter getFilter() {
    if (filter == null) {
        filter = new MyFilter();
    }
    return filter;
}
月下凄凉 2024-11-24 11:28:13

他们在这里介绍了它:
https://www.mysamplecode.com/2012/ 07/android-listview-custom-layout-filter.html

您需要在arrrat适配器上调用clear(),以免在每个元素上调用indexBoundException和add(),因为addAll() 仅自 honeycomb 起才有效。

@SuppressWarnings(“未选中”)
@覆盖
protected voidpublishResults(CharSequence约束,
FilterResults 结果){

countryList = (ArrayList<Country>)results.values;
notifyDataSetChanged();
clear();
for(int i = 0, l = countryList.size(); i < l; i++)
 add(countryList.get(i));
notifyDataSetInvalidated();

}

They have it covered here:
https://www.mysamplecode.com/2012/07/android-listview-custom-layout-filter.html

You'll need to call clear() on the arrrat adapter to not hit the indexBoundException and add() on every element, since addAll() is valid only since honeycomb.

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

countryList = (ArrayList<Country>)results.values;
notifyDataSetChanged();
clear();
for(int i = 0, l = countryList.size(); i < l; i++)
 add(countryList.get(i));
notifyDataSetInvalidated();

}

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文