RecyclerView悬浮吸顶Header,支持点击事件与状态绑定。
依赖compile'com.yuyang:stickyheaders:1.0.0'用法HeaderModelHeaderModel需要实现 StickyHeaderModel 接口
publicclassHeaderItemimplementsStickyHeaderModel{publicfinalStringtitle;/***状态保存示例,如果header存在一些交互性行为,在onBindViewHolder里面需要绑定悬浮header的状态*/publicintcolor=0xff777777;publicHeaderItem(Stringtitle){this.title=title;}}publicclassItem{publicfinalStringtitle;publicfinalStringmessage;publicItem(Stringtitle,Stringmessage){this.title=title;this.message=message;}}AdapterRecyclerViewAdapter需要实现 StickyHeaderProvider 接口,并在 getAdapterData() 返回model数据,用于判断对应position是否为Header
publicfinalclassRecyclerAdapterextendsRecyclerView.Adapter<RecyclerAdapter.BaseViewHolder>implementsStickyHeaderProvider{privatefinalList<Object>dataList=newArrayList<>();@OverridepublicBaseViewHolderonCreateViewHolder(ViewGroupparent,intviewType){if(viewType==0){returnnewItemViewHolder(LayoutInflater.from(parent.getContext()).inflate(R.layout.item_view,parent,false));}else{returnnewHeaderViewHolder(LayoutInflater.from(parent.getContext()).inflate(R.layout.header_view,parent,false));}}@OverridepublicvoidonBindViewHolder(finalBaseViewHolderholder,finalintposition){}@OverridepublicintgetItemCount(){returndataList.size();}@OverridepublicintgetItemViewType(intposition){returndataList.get(position)instanceofItem?0:1;}@OverridepublicList<?>getAdapterData(){returndataList;}privatestaticfinalclassItemViewHolderextendsBaseViewHolder{TextViewtitleTextView;TextViewmessageTextView;ItemViewHolder(ViewitemView){super(itemView);titleTextView=itemView.findViewById(R.id.tv_title);messageTextView=itemView.findViewById(R.id.tv_message);}}privatestaticfinalclassHeaderViewHolderextendsBaseViewHolder{TextViewtitleTextView;TextViewbutton;HeaderViewHolder(ViewitemView){super(itemView);titleTextView=itemView.findViewById(R.id.tv_title);button=itemView.findViewById(R.id.button);}}staticclassBaseViewHolderextendsRecyclerView.ViewHolder{BaseViewHolder(ViewitemView){super(itemView);}}}RecyclerViewRecyclerViewrecyclerView=findViewById(R.id.recycler_view);RecyclerAdapteradapter=newRecyclerAdapter();adapter.setDataList(genDataList(0));//StickyLinearLayoutManager替代LinearLayoutManagerStickyLinearLayoutManagerlayoutManager=newStickyLinearLayoutManager(this,adapter);recyclerView.setLayoutManager(layoutManager);recyclerView.setAdapter(adapter);
评论