且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何排序和过滤字符串数组?

更新时间:2023-01-30 13:41:32

这是我的操作方式。

我创建了另一个 ArrayList< Integer> 和2个 List< Array> ,最后它们是变量:

I created another ArrayList<Integer> and 2 List<Array>, at the end they were the "variables:

private ArrayList<Integer> drawables, mFiltered;
private String[] brands;
private List<String> stringList, mFilteredNames;
int resId;

然后在启动适配器时,我

Then when "starting" the adapter, I sorted the string array this way:

stringList = new ArrayList<String>(Arrays.asList(brands));
Collections.sort(stringList);
loadLogo(stringList);

新的loadLogo无效是:

The new loadLogo void is:

private void loadLogo(List<String> list) {
        drawables = new ArrayList<>();

        for (String extra : list) {
            int res = r.getIdentifier(extra, "drawable", p);
            if (res != 0) {
                final int brandInt = r.getIdentifier(extra, "drawable", p);
                if (brandInt != 0)
                    drawables.add(brandInt);
            }
        }
    }

这是我的过滤功能:

public synchronized void filter(CharSequence s) {
        if (s == null || s.toString().trim().isEmpty()) {
            if (mFiltered != null) {
                mFiltered = null;
                notifyDataSetChanged();
            }
        } else {
            if (mFiltered != null)
                mFiltered.clear();
            mFiltered = new ArrayList<>();
            mFilteredNames = new ArrayList<String>();
            for (int i = 0; i < stringList.size(); i++) {
                final String name = stringList.get(i);
                if (name.toLowerCase(Locale.getDefault())
                        .startsWith(s.toString().toLowerCase(Locale.getDefault()))) {
                    mFiltered.add(drawables.get(i));
                    mFilteredNames.add(name);
                }
            }
            notifyDataSetChanged();
        }

并在 onBindViewHolder RecyclerView 适配器的方法,我这样写:

And in the onBindViewHolder method of the RecyclerView adapter, I wrote this:

if (mFiltered != null) {
            resId = mFiltered.get(position);
            holder.logo.setImageResource(resId);
        } else {
            resId = drawables.get(position);
            holder.logo.setImageResource(resId);
        }

我不知道这是否是正确的方法为我的目的而努力。如果有人有更好的答案,我将不胜感激。

I don't know if it's the right way to do it, but is working for my purpose. If someone has a better answer I will be thankful.

此外,我不知道这对其他人有多大用处,因为它主要用于自定义目的,但我希望这对其他人也有帮助。

Also, I don't know how useful this could be for other people as it is mostly for a custom purpose, but I hope this helps someone else too.