如何在回收视图中制作部分?

时间:2016-07-21 18:26:13

标签: android android-recyclerview

我花了很多时间搜索回收多类型视图。我已经使用了回收视图的导航抽屉,我使用两个视图一个用于标题,一个用于菜单项。现在我需要膨胀两个数组列表,如第一个用于“功能”项目,另一个用于回收视图中的“正常”项目列表。在这种情况下,我需要在回收视图中首先创建两个部分,用于“功能”项目完成后功能项目,需要为正常项目制作另一个部分。我怎么能得到这个?任何想法?

1 个答案:

答案 0 :(得分:1)

您可以使用库SectionedRecyclerViewAdapter将数据分组到各个部分。

首先创建一个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 SimpleHeaderViewHolder(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("Feature", firstDataList);
MySection section2 = new MySection("Normal", secondDataList);

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

// Set up your RecyclerView with the SectionedRecyclerViewAdapter
RecyclerView recyclerView = (RecyclerView) findViewById(R.id.recyclerview);
recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
recyclerView.setAdapter(sectionAdapter);