我一直在使用 cursor 和 recyclerview。
我有一个查询游标对象(从加载程序传递)和一个 header 字符串数组[]。
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 会一个接一个地对齐标题和游标数据。
想要探索使用正确的标题和项目位置实现最终光标的方法。
最佳答案
您可以使用图书馆 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);
}
}
然后您使用您的 Sections 设置 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>
.
关于android - Recyclerview,CursorAdapter,中间有 Header View ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41475128/