RecyclerView适配器,包含2个部分,基于数据集中的字段

时间:2016-06-17 11:13:33

标签: android-recyclerview

我有一个List传递给RecyclerView。 WifiNetwork对象包含一个布尔值" inRange"。

在我的RecyclerView中,我想要这个结构: - 标题:IN RANGE - boolean inRange == true的项目 - 标题:不在范围内 - 具有布尔值inRange == false

的项目

我似乎找不到一个简单的方法来做到这一点。

我尝试了什么: - 制作"在范围内" &安培; "范围内没有"标签直接进入我的Activity并使用了2个RecyclerViews(这很难看) - afollestad的sectioned-recyclerview(对我来说有点不清楚)

这一定非常普遍。你是怎么解决这个问题的?

1 个答案:

答案 0 :(得分:0)

您可以使用库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("IN RANGE", inRangeDataList);
MySection section2 = new MySection("NOT IN RANGE", notInRangeDataList);

// 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);