【问题标题】:What is the SortedList<T> working with RecyclerView.Adapter?什么是 SortedList<T> 与 RecyclerView.Adapter 一起使用?
【发布时间】:2015-04-22 10:54:02
【问题描述】:

Android 支持库 22.1 已于昨天发布。 v4 支持库和 v7 中添加了许多新功能,其中android.support.v7.util.SortedList&lt;T&gt; 引起了我的注意。

据说SortedList是一个新的数据结构,与RecyclerView.Adapter一起工作,维护RecyclerView提供的item添加/删除/移动/更改动画。这听起来像ListView 中的List&lt;T&gt;,但似乎更先进、更强大。

那么,SortedList&lt;T&gt; 和 List&lt;T&gt; 有什么区别?我怎样才能有效地使用它?如果是这样,SortedList&lt;T&gt; 对List&lt;T&gt; 的执行是什么?有人可以发布一些样本吗?

任何提示或代码将不胜感激。提前致谢。

【问题讨论】:

  • 它必须是一个基于泛型 T 的 Comparable 实现排序的列表 - 如果不是,那么 google 在命名约定部门失去了一些分数。
  • 它是一个根据比较回调对元素进行排序的列表。所以你可以添加元素,它们会出现在“正确”的位置(而不是最后)。看一下Javadoc。 developer.android.com/reference/android/support/v7/util/…
  • 最重要的是,如何与RecyclerView.Adapter一起使用?有人写过这方面的样本吗?

标签: android android-appcompat android-recyclerview sortedlist


【解决方案1】:

SortedList 通过Callback 处理与 Recycler 适配器的通信。

SortedList 和 List 之间的一个区别可以在下面示例中的 addAll 辅助方法中看到。

public void addAll(List<Page> items) {
        mPages.beginBatchedUpdates();
        for (Page item : items) {
            mPages.add(item);
        }
        mPages.endBatchedUpdates();
    }
  1. 保留最后添加的项目

假设我有 10 个缓存项目要在我的回收站列表被填充后立即加载。同时,我在我的网络中查询相同的 10 个项目,因为在我缓存它们之后它们可能已经改变。我可以调用相同的 addAll 方法,SortedList 将在后台用 fetchedItems 替换 cachedItems(始终保留最后添加的项目)。

// After creating adapter
myAdapter.addAll(cachedItems)
// Network callback
myAdapter.addAll(fetchedItems)

在常规的List 中,我的所有项目都会重复(列表大小为 20)。使用SortedList,它使用回调的areItemsTheSame 替换相同的项目。

  1. 它很聪明地知道何时更新视图

添加 fetchedItems 时,onChange 仅在 Page 的一个或多个标题发生更改时才会被调用。您可以自定义 SortedList 在回调的 areContentsTheSame 中查找的内容。

  1. 性能卓越

如果要将多个项目添加到 SortedList,如果将项目添加到连续索引中,BatchedCallback 调用会将单个 onInserted(index, 1) 调用转换为一个 onInserted(index, N) 调用。此更改可以帮助 RecyclerView 更轻松地解决更改。

示例

您可以在您的适配器上为您的SortedList 添加一个 getter,但我只是决定向我的适配器添加辅助方法。

适配器类:

  public class MyAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
    private SortedList<Page> mPages;

    public MyAdapter() {
        mPages = new SortedList<Page>(Page.class, new SortedList.Callback<Page>() {
            @Override
            public int compare(Page o1, Page o2) {
                return o1.getTitle().compareTo(o2.getTitle());
            }

            @Override
            public void onInserted(int position, int count) {
                notifyItemRangeInserted(position, count);
            }

            @Override
            public void onRemoved(int position, int count) {
                notifyItemRangeRemoved(position, count);
            }

            @Override
            public void onMoved(int fromPosition, int toPosition) {
                notifyItemMoved(fromPosition, toPosition);
            }

            @Override
            public void onChanged(int position, int count) {
                notifyItemRangeChanged(position, count);
            }

            @Override
            public boolean areContentsTheSame(Page oldItem, Page newItem) {
                // return whether the items' visual representations are the same or not.
                return oldItem.getTitle().equals(newItem.getTitle());
            }

            @Override
            public boolean areItemsTheSame(Page item1, Page item2) {
                return item1.getId() == item2.getId();
            }
        });

    }

    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext())
                .inflate(R.layout.viewholder_page, parent, false);
        return new PageViewHolder(view);
    }

    @Override
    public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
        PageViewHolder pageViewHolder = (PageViewHolder) holder;
        Page page = mPages.get(position);
        pageViewHolder.textView.setText(page.getTitle());
    }

    @Override
    public int getItemCount() {
        return mPages.size();
    }

    // region PageList Helpers
    public Page get(int position) {
        return mPages.get(position);
    }

    public int add(Page item) {
        return mPages.add(item);
    }

    public int indexOf(Page item) {
        return mPages.indexOf(item);
    }

    public void updateItemAt(int index, Page item) {
        mPages.updateItemAt(index, item);
    }

    public void addAll(List<Page> items) {
        mPages.beginBatchedUpdates();
        for (Page item : items) {
            mPages.add(item);
        }
        mPages.endBatchedUpdates();
    }

    public void addAll(Page[] items) {
        addAll(Arrays.asList(items));
    }

    public boolean remove(Page item) {
        return mPages.remove(item);
    }

    public Page removeItemAt(int index) {
        return mPages.removeItemAt(index);
    }

    public void clear() {
       mPages.beginBatchedUpdates();
       //remove items at end, to avoid unnecessary array shifting
       while (mPages.size() > 0) {
          mPages.removeItemAt(mPages.size() - 1);
       }
       mPages.endBatchedUpdates();
    }
}

页面类:

public class Page {
    private String title;
    private long id;

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public long getId() {
        return id;
    }

    public void setId(long id) {
        this.id = id;
    }
}

Viewholder xml:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content">

    <TextView
        android:id="@+id/text_view"
        style="@style/TextStyle.Primary.SingleLine"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />

</LinearLayout>

Viewholder 类:

public class PageViewHolder extends RecyclerView.ViewHolder {
    public TextView textView;


    public PageViewHolder(View itemView) {
        super(itemView);
        textView = (TextView)item.findViewById(R.id.text_view);
    }
}

【讨论】:

  • 使用SortedList作为RecyclerView.Adapter的字段是不是最好的方式?
  • 我会说由程序员决定哪种设计最适合他们。就我而言,让适配器处理所有数据并让SortedList 在内部表示数据更有意义。
  • 注意有SortedListAdapterCallback,它接受RecyclerView.Adapter作为构造函数参数,为你处理onInserted()和kin方法。
  • 实现错误。它打破了 equals() 和 compareTo() 之间的约定。如果元素相等,则必须检查 compareTo() 并在比较标题之前返回 0。否则,您最终会遇到与 SortedList 一样重复的场景,因为它依赖于合同。
  • 当更新项目时,我有 new、updated 和 DELETED 项目,您将如何处理? .addAll 不会有帮助,因为它不会删除现在删除的项目,.clear() 将“重置”列表(我需要检查这个)。 .beginBatchUpdate 可以通过封装.remove() 的循环和.addAll() 来提供帮助吗?
【解决方案2】:

SortedList 在v7 support library 中。

一个SortedList 实现,可以保持项目有序,还 通知列表中的更改,以便它可以绑定到 RecyclerView.Adapter.

它使用compare(Object, Object) 方法和 使用二分搜索检索项目。如果您的排序标准 项目可能会发生变化,请确保在编辑时调用适当的方法 以避免数据不一致。

您可以通过 SortedList.Callback参数。

下面是SortedList的使用示例,我想这就是你想要的,看看它,享受吧!

public class SortedListActivity extends ActionBarActivity {
    private RecyclerView mRecyclerView;
    private LinearLayoutManager mLinearLayoutManager;
    private SortedListAdapter mAdapter;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.sorted_list_activity);
        mRecyclerView = (RecyclerView) findViewById(R.id.recycler_view);
        mRecyclerView.setHasFixedSize(true);
        mLinearLayoutManager = new LinearLayoutManager(this);
        mRecyclerView.setLayoutManager(mLinearLayoutManager);
        mAdapter = new SortedListAdapter(getLayoutInflater(),
                new Item("buy milk"), new Item("wash the car"),
                new Item("wash the dishes"));
        mRecyclerView.setAdapter(mAdapter);
        mRecyclerView.setHasFixedSize(true);
        final EditText newItemTextView = (EditText) findViewById(R.id.new_item_text_view);
        newItemTextView.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView textView, int id, KeyEvent keyEvent) {
                if (id == EditorInfo.IME_ACTION_DONE &&
                        (keyEvent == null || keyEvent.getAction() == KeyEvent.ACTION_DOWN)) {
                    final String text = textView.getText().toString().trim();
                    if (text.length() > 0) {
                        mAdapter.addItem(new Item(text));
                    }
                    textView.setText("");
                    return true;
                }
                return false;
            }
        });
    }

    private static class SortedListAdapter extends RecyclerView.Adapter<TodoViewHolder> {
        SortedList<Item> mData;
        final LayoutInflater mLayoutInflater;
        public SortedListAdapter(LayoutInflater layoutInflater, Item... items) {
            mLayoutInflater = layoutInflater;
            mData = new SortedList<Item>(Item.class, new SortedListAdapterCallback<Item>(this) {
                @Override
                public int compare(Item t0, Item t1) {
                    if (t0.mIsDone != t1.mIsDone) {
                        return t0.mIsDone ? 1 : -1;
                    }
                    int txtComp = t0.mText.compareTo(t1.mText);
                    if (txtComp != 0) {
                        return txtComp;
                    }
                    if (t0.id < t1.id) {
                        return -1;
                    } else if (t0.id > t1.id) {
                        return 1;
                    }
                    return 0;
                }

                @Override
                public boolean areContentsTheSame(Item oldItem,
                        Item newItem) {
                    return oldItem.mText.equals(newItem.mText);
                }

                @Override
                public boolean areItemsTheSame(Item item1, Item item2) {
                    return item1.id == item2.id;
                }
            });
            for (Item item : items) {
                mData.add(item);
            }
        }

        public void addItem(Item item) {
            mData.add(item);
        }

        @Override
        public TodoViewHolder onCreateViewHolder(final ViewGroup parent, int viewType) {
            return new TodoViewHolder (
                    mLayoutInflater.inflate(R.layout.sorted_list_item_view, parent, false)) {
                @Override
                void onDoneChanged(boolean isDone) {
                    int adapterPosition = getAdapterPosition();
                    if (adapterPosition == RecyclerView.NO_POSITION) {
                        return;
                    }
                    mBoundItem.mIsDone = isDone;
                    mData.recalculatePositionOfItemAt(adapterPosition);
                }
            };
        }

        @Override
        public void onBindViewHolder(TodoViewHolder holder, int position) {
            holder.bindTo(mData.get(position));
        }

        @Override
        public int getItemCount() {
            return mData.size();
        }
    }

    abstract private static class TodoViewHolder extends RecyclerView.ViewHolder {
        final CheckBox mCheckBox;
        Item mBoundItem;
        public TodoViewHolder(View itemView) {
            super(itemView);
            mCheckBox = (CheckBox) itemView;
            mCheckBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
                @Override
                public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                    if (mBoundItem != null && isChecked != mBoundItem.mIsDone) {
                        onDoneChanged(isChecked);
                    }
                }
            });
        }

        public void bindTo(Item item) {
            mBoundItem = item;
            mCheckBox.setText(item.mText);
            mCheckBox.setChecked(item.mIsDone);
        }

        abstract void onDoneChanged(boolean isChecked);
    }

    private static class Item {
        String mText;
        boolean mIsDone = false;
        final public int id;
        private static int idCounter = 0;

        public Item(String text) {
            id = idCounter ++;
            this.mText = text;
        }
    }
}

【讨论】:

  • 很抱歉几个月后对此发表评论,但是,当添加一些导致回收的物品时,是否只有我遇到了一些严重的问题?如果我添加 12 个项目,它会发疯并开始触发一些动作,另外,它会删除所有以前输入的数据...
  • 对不起,我的意思是示例代码,让我详细说明一下。也许最好单独问一个问题。
  • TL;DR:在构建 SortedList&lt;&gt; 时使用 SortedListAdapterCallback
【解决方案3】:

支持库源代码库中有一个示例 SortedListActivity,它演示了如何在 RecyclerView.Adapter 中使用 SortedList 和 SortedListAdapterCallback。从 SDK 的根目录开始,安装了支持库后,它应该位于 extras/android/support/samples/Support7Demos/src/com/example/android/supportv7/util/SortedListActivity.java(也位于 github)。

这些特定样本的存在在 Google 的文档中提到了 exactly once,在处理不同主题的页面底部,所以我不怪你没有找到它。

【讨论】:

【解决方案4】:

关于SortedList 实现,它由&lt;T&gt; 数组支持,默认最小容量为10 个项目。一旦数组已满,数组的大小就会调整为size() + 10

源码可在here获取

来自documentation

一个排序列表实现,可以保持项目有序,也可以 通知列表中的更改,以便它可以绑定到 RecyclerView.Adapter。

它使用 compare(Object, Object) 方法保持项目排序,并且 使用二分搜索检索项目。如果您的排序标准 项目可能会发生变化,请确保在编辑时调用适当的方法 以避免数据不一致。

您可以通过 SortedList.Callback 参数。

关于性能,他们还添加了SortedList.BatchedCallback 以一次执行多个操作而不是一次执行一个操作

一个回调实现,可以批量通知由 排序列表。

如果你想在一个 SortedList 但不想一一分派每个事件,这可能 导致性能问题。

例如,如果您要向 SortedList 添加多个项目, BatchedCallback 调用转换单个 onInserted(index, 1) 调用 如果项目被添加到连续的一个 onInserted(index, N) 指数。此更改可以帮助 RecyclerView 更多地解决更改 很容易。

如果 SortedList 中的连续变化不适合 批处理,BatchingCallback 在这种情况下立即调度它们 检测到。完成对 SortedList 的编辑后,您必须 始终调用 dispatchLastEvent() 以刷新对回调的所有更改。

【讨论】:

  • 解释得很好。 Samples 会更好。
  • 目前我没有时间拿出一个示例,阅读文档并深入研究它。
猜你喜欢
  • 1970-01-01
  • 2011-04-09
  • 2010-09-28
  • 2011-10-29
  • 2015-04-11
  • 2013-09-01
  • 1970-01-01
  • 2017-06-13
相关资源
最近更新 更多