我想显示带有章节标题的RecyclerView。我指的是这个例子https://gist.github.com/gabrielemariotti/4c189fb1124df4556058,这很好用。但我想在任何位置插入或删除元素(带或不带节标题)。我通过扩展上面的代码尝试了一些方法。但没有找到任何最佳解决方案。有没有人解决这个问题?提前致谢
答案 0 :(得分:3)
您可以使用库SectionedRecyclerViewAdapter:
dependencies {
compile 'io.github.luizgrp.sectionedrecyclerviewadapter:sectionedrecyclerviewadapter:1.+'
}
class MySection extends StatelessSection {
ArrayList<String> myList = new ArrayList<>(10);
public MySection() {
// call constructor with layout resources for this Section header and items
super(R.layout.section_header, R.layout.section_item);
}
public void addItem(int position, String item) {
myList.add(position, item);
}
public void removeItem(int position) {
myList.remove(position);
}
@Override
public int getContentItemsTotal() {
return myList.size();
}
@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(myList.get(position));
}
}
class MyItemViewHolder extends RecyclerView.ViewHolder {
private final TextView tvItem;
public MyItemViewHolder(View itemView) {
super(itemView);
tvItem = (TextView) itemView.findViewById(R.id.tvItem);
}
}
// Create an instance of SectionedRecyclerViewAdapter
SectionedRecyclerViewAdapter sectionAdapter = new SectionedRecyclerViewAdapter();
MySection mySection = new MySection();
// Add your Sections
sectionAdapter.addSection(mySection);
// Set up your RecyclerView with the SectionedRecyclerViewAdapter
RecyclerView recyclerView = (RecyclerView) findViewById(R.id.recyclerview);
recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
recyclerView.setAdapter(sectionAdapter);
mySection.addItem(1, "Item 1");
mySection.remove(0);
sectionAdapter.notifyDataSetChanged();