RecyclerView在卡片视图中与标题

时间:2016-10-07 19:22:54

标签: android android-recyclerview android-cardview

我希望在我的应用程序中显示一个足球比赛列表,其中包含日期时间标题。

在我的情况下,我想在卡片视图中显示日期类别中的游戏,并设置一个显示日期但在卡片视图外侧的标题。

通过添加卡片视图作为我的RecyclerView父级,CardView中显示日期标题。当我将CardView作为我的ViewType父母添加到卡中显示的每个项目时。

如何创建如下picture

之类的列表

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

// Add your Sections to the adapter
sectionAdapter.addSection(new MySection("Indonesia Super League", firstDataList));
sectionAdapter.addSection(new MySection("Regionalliga West", secondDataList));
sectionAdapter.addSection(new MySection("Club Friendly Games", thirdDataList));

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