带分区标题的RecyclerView项目(任意位置元素的动态更新)

时间:2015-12-25 13:29:03

标签: android android-recyclerview material-design

我想显示带有章节标题的RecyclerView。我指的是这个例子https://gist.github.com/gabrielemariotti/4c189fb1124df4556058,这很好用。但我想在任何位置插入或删除元素(带或不带节标题)。我通过扩展上面的代码尝试了一些方法。但没有找到任何最佳解决方案。有没有人解决这个问题?提前致谢

1 个答案:

答案 0 :(得分:3)

您可以使用库SectionedRecyclerViewAdapter

1)添加gradle依赖:

dependencies {
    compile 'io.github.luizgrp.sectionedrecyclerviewadapter:sectionedrecyclerviewadapter:1.+'
}

2)创建自定义Section类:

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));
    }
}

3)为项目创建自定义ViewHolder:

class MyItemViewHolder extends RecyclerView.ViewHolder {

    private final TextView tvItem;

    public MyItemViewHolder(View itemView) {
        super(itemView);

        tvItem = (TextView) itemView.findViewById(R.id.tvItem);
    }
}

4)使用SectionedRecyclerViewAdapter设置ReclyclerView

// 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);

5)在章节中添加/删除您的项目:

mySection.addItem(1, "Item 1");
mySection.remove(0);

sectionAdapter.notifyDataSetChanged();