如何有效地在 RecyclerView 项目中添加子列表,例如在 Google Keep 应用程序中?

How can I add child lists inside RecyclerView items efficiently, like in the Google Keep app?

我正在尝试创建一个 RecyclerView,其中包含网格中的各种模块,其中一些模块包含子项列表。如何添加这些子列表而不会在用户滚动时造成卡顿?

我已经尝试将 LinearLayout 添加到我的 ViewHolder,并在 onBindViewHolder 中手动扩充子视图,以及使用嵌套的 RecyclerView。两者都有性能问题,并且嵌套的 RecyclerViews 有 wrap_content 不好玩的附加问题。

有什么优化性能的建议吗?我是否缺少更好的方法?

@Override
public int getItemViewType(int position) {
    return modules.get(position).getType().ordinal();
}

@Override
public ModuleViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
    switch (types[viewType]) {
        case LINEARLAYOUTSTATBLOCK:
            return new ModuleLLBlockViewHolder(LayoutInflater.from(parent.getContext()).inflate(R.layout.module_block, parent, false));
        case RECYCLERVIEWSTATBLOCK:
            return new ModuleRVBlockViewHolder(LayoutInflater.from(parent.getContext()).inflate(R.layout.module_block, parent, false));
    }
}

@Override
public void onBindViewHolder(ModuleViewHolder vh, final int position) {
    switch (types[vh.getItemViewType()]) {
        case LINEARLAYOUTSTATBLOCK:
            bind((ModuleLLBlockViewHolder) vh, (StatBlockModule) modules.get(position));
            break;
        case RECYCLERVIEWSTATBLOCK:
            bind((ModuleRVBlockViewHolder) vh, (StatBlockModule) modules.get(position));
            break;
    }
}

private void bind(ModuleLLBlockViewHolder vh, TitleTextBlockModule module) {
    for (int i = 0; i < module.getStats().size(); i++) {
        View v = LayoutInflater.from(vh.linearLayout.getContext()).inflate(R.layout.row, vh.linearLayout, true);
        v.setId(i);
        TextView tvCategory = (TextView) v.findViewById(R.id.tvCategory);
        CustomView customView = (CustomView) v.findViewById(R.id.customView);
        tvCategory.setText(stat.getCategory());
        customView.setRating(stat.getRating());
    }
}

private void bind(ModuleRVBlockViewHolder vh, StatBlockModule module) {
    vh.childRecyclerView.setLayoutManager(new LinearLayoutManager(vh.itemView.getContext()));
    vh.childRecyclerView.setAdapter(new ChildAdapter(module.getStats()));
}

有了 Android Support Library 23.2,RecyclerView 现在服从 wrap_content,因此它可以在列表项中使用。

您应该在内部 RecyclerView 上设置 android:nestedScrollingEnabled="false",以便滚动由外部 RecyclerView 单独处理。