Android Recycleview Use detailed

Source: Internet
Author: User


I. Brief introduction of Recycleview

Recycleview is a new component in the SUPPORT-V7 package and is a powerful sliding component. Compared to the ListView and GridView, there are many advantages that developers like: data binding, item creation and view recovery reuse mechanism. But Recycleview is more advanced and flexible, and it can be very well displayed when our data is changed because of user events or network events. The most important feature of Recycleview is reuse.
Second, Recycleview and listview Difference

The Recycleview is an upgraded version of the ListView, which also has the Recycle function of item as compared to the classic ListView.

1.RecycleView encapsulates the recycling of Viewholder, standardizes the Viewholder, writes adapter-oriented Viewholder, rather than view, highly decoupled, multiplexed logic is encapsulated to bring greater convenience to writing code.

2.RecycleView provides a plug-and-play experience, highly decoupled, exceptionally flexible, in order to control the display of the item, Recycleview specifically extracts the corresponding class for the display of an item, making it very extensible.

3. You can control the item increase or decrease animation, can be controlled by itemanimation. Of course, Recycleview has its own default implementation method.

4. Use LayoutManager to determine how each item is arranged.

5. Before using Recycleview, you need to inherit the Recycleview.adapter adapter to bind the data to each item.

6. Use LayoutManager to determine how each item is placed, displayed, and hidden. Or when reusing view is recycled, LayoutManager recalls that the adapter requests new data to replace the previous data, which avoids creating too many view and frequent call ID methods.

Iii. Basic usage of recycle

1. Add dependencies under Project Gradle.

Compile ' com.android.support:recyclerview-v7:25.0.1 '

2. Implement the Recycleview layout.

<android.support.v7.widget.recyclerview    android:id= "@+id/id_recyclerview"    android:divider= "# ffff0000 "    android:dividerheight=" 10DP "    android:layout_width=" match_parent "    android:layout_height=" Match_parent "/>

3. Set up the layout manager. The layout mainly has three kinds of realization way, this article uses the flow type layout to parse.

Mrecyclerview.setlayoutmanager (New Linearlayoutmanager (this));    Linear layout Mrecyclerview.setlayoutmanager (new Gridlayoutmanager (this, 4));     Grid Mrecyclerview.setlayoutmanager (New        Staggeredgridlayoutmanager (4, staggeredgridlayoutmanager.vertical));     Flow layout

4. Set adapter and Viewholder for event binding.

@Overridepublic void Onbindviewholder (final myviewholder holder, int position) {    Viewgroup.layoutparams LP = Holder.tv.getLayoutParams ();    if (position! = 0 && Position < Mdatas.size ()) {        lp.height = mheights.get (position);        HOLDER.TV.SETLAYOUTPARAMS (LP);    }    Holder.tv.setText (Mdatas.get (position));}

5.setAdapter and set the split line, item animation.

Madapter = new Homeadapter (this, mdatas);        Madapter.setonitemclicklistener (this);        Mrecyclerview.setadapter (madapter);        Set default Split Line//        mrecyclerview.additemdecoration (New divideritemdecoration (this,//                divideritemdecoration.vertical));        Mrecyclerview.additemdecoration (New Dividergriditemdecoration (this));        Sets the item animation        mrecyclerview.setitemanimator (New Defaultitemanimator ());

6. Initialize the data.

private void Initlistdata () {    Mdatas = new arraylist<string> ();    for (int i = ' A '; I <= ' z '; i++) {        Mdatas.add ("" + (char) i);}    }

7. Set Item Click event (Add Item). Recycleview doesn't give me a onitemclicklistener built-in listener like a ListView, and when we click on the item to trigger the event we call back the method, but we can change the adapter to achieve our goal.

Holder.itemView.setOnClickListener (New View.onclicklistener () {    @Override public    void OnClick (view view) {        int pos = holder.getlayoutposition ();        Listener. Onitemclick (Holder.itemview, POS);        AddData (POS);    }});

public void AddData (int position) {    Mdatas.add (position, "Insert one");    notifyiteminserted (position);}

8. Set the long press Click event (remove Item). As with 7, the main thing is to use the Recycleview method to add and delete data. Unlike the ListView, the ListView uses the Notifydatasetchange method to refresh the data when the data changes, but Recycleview takes a more advanced approach notifyiteminserted (position) and notifyitemremoved (position) to add and remove data refreshes.

Holder.itemView.setOnLongClickListener (New View.onlongclicklistener () {    @Override public    Boolean Onlongclick (view view) {        int pos = holder.getlayoutposition ();        Listener.onitemlongclick (Holder.itemview, POS);        Removedata (POS);        return false;    }});

public void Removedata (int position) {    mdatas.remove (position);    notifyitemremoved (position);}

9. Encapsulation of the split line.

Package Example.com.demo_recycleview;import Android.content.context;import Android.content.res.typedarray;import Android.graphics.canvas;import Android.graphics.rect;import Android.graphics.drawable.drawable;import Android.support.v7.widget.gridlayoutmanager;import Android.support.v7.widget.recyclerview;import Android.support.v7.widget.staggeredgridlayoutmanager;import Android.view.view;public Class Dividergriditemdecoration extends Recyclerview.itemdecoration {private static final int[] Attrs = new int[] {Android.    R.attr.listdivider};    Private drawable Mdivider; Public Dividergriditemdecoration (Context context) {Final TypedArray array = context.obtainstyledattributes (ATTR        S);        Mdivider = array.getdrawable (0);    Array.recycle (); } @Override public void OnDraw (Canvas C, Recyclerview parent, recyclerview.state State) {Drawhorizontal (c        , parent);    Drawvertical (c, parent);    } private int Getspancount (Recyclerview parent) {    Number of columns int spancount =-1;        Recyclerview.layoutmanager LayoutManager = Parent.getlayoutmanager (); if (LayoutManager instanceof gridlayoutmanager) {Spancount = ((Gridlayoutmanager) layoutmanager). GetSpa        Ncount (); } else if (LayoutManager instanceof staggeredgridlayoutmanager) {Spancount = ((staggeredgridlayoutmanag        ER) layoutmanager). Getspancount ();    } return Spancount;        } public void Drawhorizontal (Canvas C, recyclerview parent) {int childCount = Parent.getchildcount ();            for (int i = 0; i < ChildCount; i++) {final View child = Parent.getchildat (i);            Final Recyclerview.layoutparams params = (recyclerview.layoutparams) child. Getlayoutparams ();            Final int left = Child.getleft ()-params.leftmargin; Final int right = Child.getright () + Params.rightmargin + Mdivider.getintrinsicwidTh ();            Final int top = Child.getbottom () + Params.bottommargin;            final int bottom = top + mdivider.getintrinsicheight ();            Mdivider.setbounds (left, top, right, bottom);        Mdivider.draw (c); }} public void Drawvertical (Canvas C, Recyclerview parent) {Final int childCount = Parent.getchildcount (        );            for (int i = 0; i < ChildCount; i++) {final View child = Parent.getchildat (i);            Final Recyclerview.layoutparams params = (recyclerview.layoutparams) child. Getlayoutparams ();            Final int top = Child.gettop ()-params.topmargin;            final int bottom = Child.getbottom () + Params.bottommargin;            Final int left = Child.getright () + Params.rightmargin;            Final int right = left + mdivider.getintrinsicwidth ();            Mdivider.setbounds (left, top, right, bottom);        Mdivider.draw (c); }} Private Boolean Islastcolum (Recyclerview Parent, int pos, int spancount, int childCount) {recyclerview.layoutmanager LA        Youtmanager = Parent.getlayoutmanager ();            if (LayoutManager instanceof Gridlayoutmanager) {if (pos + 1)% Spancount = = 0)//If this is the last column, you do not need to draw the right            {return true; }} else if (LayoutManager instanceof staggeredgridlayoutmanager) {int orientation = ((staggered            Gridlayoutmanager) LayoutManager). Getorientation (); if (orientation = = staggeredgridlayoutmanager.vertical) {if (pos + 1)% Spancount = = 0)//If it is the most                After a column, you do not need to draw the right {return true;                }} else {childCount = childcount-childcount% Spancount;            if (POS >= childCount)//If it is the last column, you do not need to draw the right return true;    }} return false; } Private BooleaN Islastraw (recyclerview parent, int pos, int spancount, int childCount) {recycler        View.layoutmanager LayoutManager = Parent.getlayoutmanager ();            if (LayoutManager instanceof gridlayoutmanager) {childCount = childcount-childcount% Spancount;        if (POS >= childCount)//If it is the last line, you do not need to draw the bottom return true; } else if (LayoutManager instanceof staggeredgridlayoutmanager) {int orientation = ((staggeredgridlayou            Tmanager) LayoutManager). Getorientation ();                Staggeredgridlayoutmanager and vertical scrolling if (orientation = = staggeredgridlayoutmanager.vertical) {                ChildCount = childcount-childcount% Spancount;            If it is the last line, you do not need to draw the bottom if (POS >= childCount) return true;   } else//Staggeredgridlayoutmanager and horizontal scrolling {//If it is the last row, you do not need to draw the bottom             if (pos + 1)% Spancount = = 0) {return true;    }}} return false; } @Override public void Getitemoffsets (Rect outrect, int itemposition, Recyclerview pa        Rent) {int spancount = Getspancount (parent);        int childCount = Parent.getadapter (). GetItemCount (); if (Islastraw (parent, Itemposition, Spancount, ChildCount))//If it is the last line, you do not need to draw the bottom {outrect.set (0, 0, Mdivi        Der.getintrinsicwidth (), 0);  } else if (Islastcolum (parent, Itemposition, Spancount, ChildCount))//If it is the last column, you do not need to draw the right {Outrect.set (0,        0, 0, mdivider.getintrinsicheight ()); } else {outrect.set (0, 0, mdivider.getintrinsicwidth (), Mdivider.getintrinsicheight (        )); }    }}


Four, the effect shows


Five, source code download   

Address: http://download.csdn.net/detail/u012721519/9743570





Good luck!

Write by Jimmy.li











Android Recycleview Use detailed

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.