我在RecyclerView内部有一个RecyclerView我添加了两个部分Favorites
,All Contacts
。要添加我使用的部分SimpleSectionedRecyclerViewAdapter
现在我的部分行是硬编码的(行和部分的索引),我想通过选择行来向favorite
部分添加行,因为没有关于我想要的内容,我没有#&# 39;知道从哪里开始或我必须做什么?
如果有人知道如何通过选择All Contacts
部分(行的默认位置)添加行。那么请给我一些关于我必须做的事情的提示
我想要的是这样的:
按下按钮
添加到收藏夹任何指导对我都有帮助,谢谢
答案 0 :(得分:0)
您可以使用库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();
// Create your sections with the list of data
MySection favoritesSection = new MySection("Favorites", favoritesList);
MySection contactsSection = new MySection("Add Favorites", contactsList);
// Add your Sections to the adapter
sectionAdapter.addSection(favoritesSection);
sectionAdapter.addSection(contactsSection);
// Set up your RecyclerView with the SectionedRecyclerViewAdapter
RecyclerView recyclerView = (RecyclerView) findViewById(R.id.recyclerview);
recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
recyclerView.setAdapter(sectionAdapter);
您可以找到如何收听按钮的示例here。
您还可以在部分中添加新行而无需重新计算索引,只需在Section类中创建这样的方法:
public void addRow(String item) {
this.list.add(item);
}
然后:
favoritesSection.addRow("new item");
sectionAdapter.notifyDataSetChanged();