在Recyclerview或Listview中添加多个标题.随机

前端之家收集整理的这篇文章主要介绍了在Recyclerview或Listview中添加多个标题.随机前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
如何在RecyclerView或listview中添加多个标题或分隔符.随机突出显示在下图中:

RecyclerView中基于日期的多个标题 – 演示图像

解决方法

您可以使用库 SectionedRecyclerViewAdapter来实现它.它具有“部分”的概念,每个部分都可以有自己的标题.

在我看来,您需要按“日期”对呼叫进行分组.所以你可以像这样创建你的Section类:

class MySection extends StatelessSection {

    String date;
    List<Call> callList;

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

        this.date = date;
        this.callList = callList;
    }

    @Override
    public int getContentItemsTotal() {
        return callList.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(callList.get(position).getContactName());
    }

    @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(date);
    }
}

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

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

MySection mySection1 = new MySection("27 Mar,2016",callList1);
MySection mySection2 = new MySection("28 Mar,callList2);

// Add your Sections
sectionAdapter.addSection(mySection1);
sectionAdapter.addSection(mySection2);

// Set up your RecyclerView with the SectionedRecyclerViewAdapter
RecyclerView recyclerView = (RecyclerView) findViewById(R.id.recyclerview);
recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
recyclerView.setAdapter(sectionAdapter);
原文链接:https://www.f2er.com/android/316412.html

猜你在找的Android相关文章