How can I implement a Material Design Expand/Collapse List on Android?

后端 未结 2 1730
一个人的身影
一个人的身影 2021-01-31 09:36

I am looking to implement a material list of this style. How can I do this on Android? What classes should I look at? Are there any existing libraries that could make implementi

2条回答
  •  耶瑟儿~
    2021-01-31 10:40

    I implemented such a list using this library:
    expandable-recycler-view

    There is a related blog, but it refers to an old version:
    Expand a RecyclerView in Four Steps

    It's basically an adapter where you can supply a list of parent elements that contain the children. You further have to specify two holders for the parents and the children. See the library's page for more details.

    class MyChild {
      // add data
    }
    class MyParentListItem implements ParentListItem {
      private final List mChildren;
    
      MyParentListItem(List children) {
        mChildren = children;
        // add other data
      }
    
      @Override
      public List getChildItemList() {
        return mChildren;
      }
    
      @Override
      public boolean isInitiallyExpanded() {
        return false;
      }
    }
    
    class MyParentViewHolder extends ParentViewHolder {
      MyParentViewHolder(View itemView) {
        super(itemView);
        // get other views with itemView.findViewById(..);
      }
    }
    
    class MyChildViewHolder extends ChildViewHolder {
      MyParentViewHolder(View itemView) {
        super(itemView);
        // get other views with itemView.findViewById(..);
      }
    }
    
    public class MyExpandableAdapter extends ExpandableRecyclerAdapter {
      private final LayoutInflater mInflater;
      public MyExpandableAdapter(List parentItemList, Context context) {
        super(parentItemList);
        mInflater = LayoutInflater.from(context);
      }
    
      @Override
      public MyParentViewHolder onCreateParentViewHolder(ViewGroup parentViewGroup) {
        final View itemView = mInflater.inflate(R.layout.parent_layout, parentViewGroup, false);
        return new MyParentViewHolder(itemView);
      }
    
      @Override
      public MyChildViewHolder onCreateChildViewHolder(ViewGroup childViewGroup) {
        final View itemView = mInflater.inflate(R.layout.child_layout, childViewGroup, false);
        return new MyChildViewHolder(itemView);
      }
    
      // bind data to holders in the onBind methods
    }
    

提交回复
热议问题