RecyclerView里面的Android RecyclerView?

时间:2016-07-20 15:26:57

标签: android android-recyclerview

我正在使用显示不同类别列表的RecyclerView。每个行项目还包含RecyclerView以显示类别项列表。父RecyclerView填充了垂直LinearLayoutManager,子RecyclerViews填充了GridLayoutManager(2列)。除{2}之外,子RecyclerViews未显示所有类别项目,即使它有许多类别项目。所有剩余的类别项目都隐藏在特定类别中。换句话说,您可以说孩子RecyclerView的扩展程度与其包含的项目不同。

我在这里找到了不同的解决方案,但没有人工作。这就是再次发布的原因。

1 个答案:

答案 0 :(得分:2)

使用此library只需一个RecyclerView即可轻松实现。见下图:

enter image description here

首先创建一个Section类:

class MySection extends StatelessSection {

    String title;
    List<String> list;

    public MySection(String title, List<String> list) {
        // call constructor with layout resources for this Section header, footer and items 
        super(R.layout.section_header, R.layout.section_item);

        this.title = title;
        this.list = list;
    }

    @Override
    public int getContentItemsTotal() {
        return list.size(); // number of items of this section
    }

    @Override
    public RecyclerView.ViewHolder getItemViewHolder(View view) {
        // return a custom instance of ViewHolder for the items of this section
        return new MyItemViewHolder(view);
    }

    @Override
    public void onBindItemViewHolder(RecyclerView.ViewHolder holder, int position) {
        MyItemViewHolder itemHolder = (MyItemViewHolder) holder;

        // bind your view here
        itemHolder.tvItem.setText(list.get(position));
    }

    @Override
    public RecyclerView.ViewHolder getHeaderViewHolder(View view) {
        return new MyHeaderViewHolder(view);
    }

    @Override
    public void onBindHeaderViewHolder(RecyclerView.ViewHolder holder) {
        MyHeaderViewHolder headerHolder = (MyHeaderViewHolder) holder;

        // bind your header view here
        headerHolder.tvItem.setText(title);
    }
}

然后使用您的章节设置RecyclerView:

// Create an instance of SectionedRecyclerViewAdapter 
SectionedRecyclerViewAdapter sectionAdapter = new SectionedRecyclerViewAdapter();

// Create your sections with the list of data for each year
MySection section1 = new MySection("Categories 1", categories1DataList);
MySection section2 = new MySection("Categories 2", categories2DataList);

// Add your Sections to the adapter
sectionAdapter.addSection(section1);
sectionAdapter.addSection(section2);

// Set up your RecyclerView with the SectionedRecyclerViewAdapter
GridLayoutManager glm = new GridLayoutManager(getContext(), 2);
glm.setSpanSizeLookup(new GridLayoutManager.SpanSizeLookup() {
    @Override
    public int getSpanSize(int position) {
        switch(sectionAdapter.getSectionItemViewType(position)) {
            case SectionedRecyclerViewAdapter.VIEW_TYPE_HEADER:
                return 2;
            default:
                return 1;
        }
    }
});
recyclerView.setLayoutManager(glm);
recyclerView.setAdapter(sectionAdapter);