20

RecyclerView已在 Android L 中引入,并且是 AppCompat v7 库的一部分。然后我决定用这个全新的应用程序更新我的应用程序RecyclerView来替换我ListView的 s. 为此,在为 设置 aLayoutManagerRecyclerView,我使用的是LinearLayoutManager,效果很好。

这是困难的事情:当我想将 my 更改ExpandableListViewRecyclerView. 由于谷歌没有创建一个“ ExpandableLayoutManager”,这很棘手,我无法做到这一点。

文档提到了孩子,但它似乎是非RecyclerView孩子本身的根视图的孩子。

有人有解决方法或一些线索吗?或者至少有一些信息,比如从哪里开始,这样我就可以实现自己的LayoutManager.

4

1 回答 1

1

可帮助您将项目分组为“部分”,然后您可以实现本示例中的展开/折叠功能。

首先你创建你的部分类:

class MySection extends StatelessSection {

    String header;
    List<String> list;
    boolean expanded = true;

    public MySection(String header, List<String> list) {
        // call constructor with layout resources for this Section header and items 
        super(R.layout.section_header, R.layout.section_item);
        this.myHeader = header;
        this.myList = list;
    }

    @Override
    public int getContentItemsTotal() {
        return expanded? list.size() : 0;
    }

    @Override
    public RecyclerView.ViewHolder getHeaderViewHolder(View view) {
        return new HeaderViewHolder(view);
    }

    @Override
    public void onBindHeaderViewHolder(RecyclerView.ViewHolder holder) {
        final HeaderViewHolder headerHolder = (HeaderViewHolder) holder;

        headerHolder.tvTitle.setText(title);

        headerHolder.rootView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                expanded = !expanded;
                headerHolder.imgArrow.setImageResource(
                        expanded ? R.drawable.ic_keyboard_arrow_up_black_18dp : R.drawable.ic_keyboard_arrow_down_black_18dp
                );
                sectionAdapter.notifyDataSetChanged();
            }
        });
    }

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

然后创建您的部分的实例并设置您的适配器:

// Create an instance of SectionedRecyclerViewAdapter 
SectionedRecyclerViewAdapter sectionAdapter = new SectionedRecyclerViewAdapter();

// Add your Sections
sectionAdapter.addSection(new MySection("Section 1", Arrays.asList(new String[] {"Item 1", "Item 2", "Item 3", "Item 4" })));
sectionAdapter.addSection(new MySection("Section 2", Arrays.asList(new String[] {"Item 1", "Item 2" })));

// Set up your RecyclerView with the SectionedRecyclerViewAdapter
RecyclerView recyclerView = (RecyclerView) findViewById(R.id.recyclerview);
recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
recyclerView.setAdapter(sectionAdapter);
于 2016-05-03T17:14:31.443 回答