Introduction
Recyclerview is the support-v7 used to replacethe LISTV iew components. The Recyclerview widget is more advanced and more flexible than the ListView. This widget is a container for displaying large datasets that can be used to perform very efficient scrolling operations by maintaining a limited number of views. If you have a data collection where the elements will change due to user actions or network events, use the Recyclerview widget.
How to use
- If you want to use Recyclerview, first add support for SUPPORT-V7.
- Open the project structure option, add the RECYCLERVIEW-V7 library in dependencies, and then use Recyclerview in your program:
Public class extends Activity { private Recyclerview rv; @Override protectedvoid onCreate (Bundle savedinstancestate) { Super. OnCreate (savedinstancestate); New Recyclerview (this); Setcontentview (RV), ... ..
- To set the layout of the Recyclerview:
Rv.setlayoutmanager (new Linearlayoutmanager (this));
Recyclerview provides these built-in layout managers:
-
- Linearlayoutmanager displays items in a vertical or horizontal scrolling list.
- Gridlayoutmanager display items in the grid.
- Staggeredgridlayoutmanager displays items in the decentralized snap grid.
Rv.setlayoutmanager (New Linearlayoutmanager (this, linearlayoutmanager.horizontal, false));//rv.setlayoutmanager (New Gridlayoutmanager (this, 2));//rv.setlayoutmanager (New Staggeredgridlayoutmanager (3, staggeredgridlayoutmanager.vertical));
- Then to add adapter to Recyclerview, this adapter also needs to be customized. In this adapter, you need to define a class that inherits from Recyclerview.viewholder:
classViewholderextendsRecyclerview.viewholder {PrivateView Root; PrivateTextView Tvtitle, tvcontent; PublicViewholder (View root) {Super(root); Tvtitle=(TextView) Root.findviewbyid (r.id.tvtitle); Tvcontent=(TextView) Root.findviewbyid (r.id.tvcontent); } PublicTextView gettvcontent () {returntvcontent; } PublicTextView Gettvtitle () {returnTvtitle; } }
- And as the return value of Oncreateviewholder, this function represents the view of each item:
@Overridepublic Recyclerview.viewholder Oncreateviewholder (viewgroup parent, int viewtype) {return new Viewholder ( Layoutinflater.from (Parent.getcontext ()). Inflate (R.layout.list_cell, null));}
- Next, rewrite Onbindviewholder, which is called when the function is used to recylerview the contents of each item.
@Overridepublic void Onbindviewholder (recyclerview.viewholder holder, int position) {Viewholder VH = (viewholder) holder ; Celldata cd = Data[position];vh.gettvtitle (). SetText (Cd.title); Vh.gettvcontent (). SetText (cd.content);}
- and provide this array, you can display:
Private celldata[] data = new celldata[]{...}
Android's Recyclerview