我一直在使用cursorler和recyclerview。
我有一个查询的游标对象(从加载器传递)和一个头字符串数组[]。
String headers[] = {"apples", "bananas"...};
现在我想将项目显示为
Apples
cursor row 1
cursor row 2
cursor row 3
Bananas
cursor row 4
cursor row 5
我不想使用getItemCount()方法进行调整。因此,计划以适当的长度传递单个光标。
一种可能的方法是使用MatrixCursor和MergeCursor添加虚拟行,如下所述:Adding rows into Cursor manually。 这很好但是MergeCursor一个接一个地对齐标题和光标数据。
想要探索使用正确的标题和项目位置来实现最终光标的方法。
答案 0 :(得分:2)
您可以使用库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.title.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(headers[0], applesList));
sectionAdapter.addSection(new MySection(headers[1], bananasList));
// Set up your RecyclerView with the SectionedRecyclerViewAdapter
RecyclerView recyclerView = (RecyclerView) findViewById(R.id.recyclerview);
recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
recyclerView.setAdapter(sectionAdapter);
通过上面的示例,您必须处理如何将Cursor
转换为List<String>
,但您可以更改MySection类以接收Cursor
而不是List<String>
}。