Use of Recyclerview (Android Development Essentials, replace ListView)

Source: Internet
Author: User
Tags recyclerview android

Use of Recyclerview (Android Development Essentials, replace ListView)when someone reads your code, says you're still using the ListView? Is it too soon to keep up with the times? Yes, today will bring you a ListView of the latest upgrade control Recyclerview,android 5.0 introduced the new control, but it is in the SUPPORT-V7 package, can be down compatible, when you learned Recyclerview, found its strong, You will be replaced by the ListView and the GridView.           Recyclerview Introduction:
Recyclerview is a new control in the SUPPORT-V7 package, is the upgraded version of the ListView, using methods and fundamentals similar to the ListView, the difference is that Recycleview forcibly put the ListView in the GetView () method is split, the Viewholder is packaged separately, only need to implement the custom definition of the Viewholder, the reorganization will help us automatically recycle each item.
Advantages of Recyclerview vs. ListView:
1, You can use the Layout manager LayoutManager to manage the display of Recyclerview: horizontal, vertical, network, grid staggered layout;
2, custom item's partition bar, realizes the custom (does not know is the advantage or the disadvantage, the opinion bar ( ̄▽ ̄) ");
3, can control the addition and deletion of item animation, very free, can be customized animation, with specific scenes, the effect is very good;
4, can dynamically add and delete an item in the specified location, and the list will not go back to the top, dynamic update list data (very much needed);     5, Disadvantage: is no onitemclicklistenter (), need their own in Recycleview internal custom list item Click event or long press the event (add on demand);       6, in material design and CardView (and Recycleview also appear new control) with the use of the display is very prominent (now many new mainstream apps have used this structure, there will be demo show).

Recycleview Basic steps to use:
       1. Mock object and Get object collection data (this is just analog data)
Package com.world.hello.recycleview;/** * Mock Object Data * Created by Chengguo on 2016/5/30. */public class SampleModel {    private String message;    Public SampleModel (String message) {        this.message = message;    }    public void Setmessage (String s) {        message = s;    }    Public String GetMessage () {        return message;    }}

Package Com.world.hello.recycleview;import java.util.arraylist;/** * Analog Data set * Created by Chengguo on 2016/5/30. */public class DemoApp {    //Get the data to be displayed (initialize data) public    static arraylist<samplemodel> getsampledata (int size) {        arraylist<samplemodel> sampleData = new arraylist<samplemodel> (size);        for (int i = 0; i < size; i++) {            sampledata.add (new SampleModel ("list item" + i));        }                return sampleData;}    }
2. Draw a split bar between list items
Using the Recyclerview control typically requires that you specify a split bar for the list item. The principle of custom split bars is to write a subclass of Recyclerview.itemdecoration and implement the Ondrawover method, in which the split bars between all the list items need to be drawn. As shown below:
Package Com.world.hello.recycleview;import Android.content.context;import Android.content.res.typedarray;import Android.graphics.canvas;import Android.graphics.drawable.drawable;import Android.support.v7.widget.RecyclerView; Import android.view.view;/** * Custom Split Line * Created by Chengguo on 2016/5/30. */public class Sampledivider extends Recyclerview.itemdecoration {//default partition bar drawable resource ID private static final int[] A Ttrs = {Android.    R.attr.listdivider};    The Drawable object of the split bar is private drawable mdicider;        Public Sampledivider (Context context) {TypedArray ta = context.obtainstyledattributes (attrs);        Gets the Drawable object of the split bar Mdicider = ta.getdrawable (0);    Recycling TA occupied space ta.recycle (); }/** * The partition bar between all the list items is drawn in the modification method * * @param c * @param parent */@Override public void Ondrawover (        Canvas C, Recyclerview Parent) {//Gets the distance of the list item distance from the left source int = Parent.getpaddingleft (); Gets the distance of the list item from the right source, int. = Parent.getwidth ()- Parent.getpaddingright ();        Gets the total number of lists int childCount = Parent.getchildcount (); Start drawing the split line between these list items for (int i = 0; i < ChildCount; i++) {//Get the current list View child = Parent.get            Childat (i);            Gets the layout parameter information for the current list item recyclerview.layoutparams params = (recyclerview.layoutparams) child.getlayoutparams ();            Calculates the ordinate int top of the upper-left corner of the splitter bar = Child.getbottom () + Params.bottommargin;            Calculates the ordinate int bottom = top + mdicider.getintrinsicheight () in the lower-right corner of the splitter bar;            Sets the position of the split bar to draw Mdicider.setbounds (Left,top,right,bottom);        Starts drawing the split bar below the current list item mdicider.draw (c); }    }}
3. Realizing adapter class
Just as the ListView Adapter generally inherits Baseadapter, Recyclerview also provides such a base class Recyclerview.adapter that the base class supports generics and generics are used to specify the controls in the list item. As follows:

Package Com.world.hello.recycleview;import Android.support.v7.widget.recyclerview;import Android.view.layoutinflater;import Android.view.view;import Android.view.viewgroup;import Android.widget.TextView ; Import Java.util.arraylist;import java.util.random;/** * Recycleview Adapter * Created by Chengguo on 2016/5/30. */public class Samplerecycleadapter extends recyclerview.adapter<samplerecycleadapter.viewholder>{//Save list item data p    Rivate final Arraylist<samplemodel> sampleData = Demoapp.getsampledata (30);        Creates a control object that is displayed in a list item (you need to specify a generic using adapter) @Override public Viewholder Oncreateviewholder (viewgroup parent, int viewtype) { Gets the list item control Linearlayer object View Rowview = Layoutinflater.from (Parent.getcontext ()). Inflate (R.layout.list_item,pare        Nt,false);    return new Viewholder (Rowview); }//Set the value displayed in the list item in the method @Override public void Onbindviewholder (viewholder holder, int position) {SampleModel        RowData = Sampledata.get (position); Holder.textviewSample.settext (Rowdata.getmessage ());    Holder.itemView.setTag (RowData);    }//sets the sum of list items @Override public int GetItemCount () {return sampledata.size ();        }//delete data for the specified list item public void Removedata (int position) {sampledata.remove (position);    Notifies Recycleview that a list item has been deleted notifyitemremoved (position); }//Add a new list item at the specified location public void AddItem (int position) {//Use random number Sampledata.add (Position,new samplemode        L ("new list item" + New Random (). Nextint (100));    notifyiteminserted (position); The/** * Viewholder is used to store the controls displayed in the list item (there is only one textview for example) */public static class Viewholder extends RECYCLERVIEW.V        iewholder{private TextView textviewsample;            Public Viewholder (View Itemview) {super (Itemview);        Textviewsample = (TextView) Itemview.findviewbyid (R.id.text_view); }    }
}

Note: All methods in the Samplerecycleradapter class that use @override are overridden by the same name method of the parent class. The methods in these methods are somewhat different from those in the ListView corresponding to the adapter, and in the new adapter there is no GetView () method, but the Oncreateviewholder and Onbindviewholder methods are used instead. The former is used to get the list item control, which specifies the data to display in the control. There is a change in the previous data, can only call the Notifydatasetchanged () method to notify the data is changed, you can now use the notifyitemremoved () method to tell the specific location of the data is removed, Use the notifyiteminserted () method to notify a new list of nape additions. There are a lot of new APIs are very practical, such as the following picture, do not introduce each;


4. Use Recyclerview in activity
Recycleview is a control in the Android support library, so you need to add the following dependencies in the gradle of the app in Android studio
' com.android.support:design:23.4.0 '
You can then use the Recycleview control, where the Recycleview dynamic add and delete operations are implemented. Slightly more complex than the ListView, to set the arrangement of the Recycleview, the split line between item, item increment and delete animation, the use of code as follows:
Package Com.world.hello.recycleview;import Android.app.activity;import Android.os.bundle;import Android.support.design.widget.floatingactionbutton;import Android.support.v7.widget.defaultitemanimator;import Android.support.v7.widget.linearlayoutmanager;import Android.support.v7.widget.recyclerview;import Android.view.view;import Android.view.animation.animationutils;import Android.widget.button;public Class    Mainactivity extends Activity {//Top Delete button private button mdeletebar;    Recyclerview private Recyclerview Mrecyclerview; Add the item button, which is also used as a button using a new control inside the design library.    It's just a nice style. Private Floatingactionbutton maddbtn;        @Override protected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate);        Setcontentview (R.layout.activity_main);        Mdeletebar = (Button) Findviewbyid (R.ID.DELETE_BTN);        MADDBTN = (Floatingactionbutton) Findviewbyid (R.id.add_item); Get to Recyclerview Mrecyclerview = (recyclerview) Findviewbyid(R.id.recycler_view);        Create Linearlayoutmanager final Linearlayoutmanager LayoutManager = new Linearlayoutmanager (this);        Specifies the Layout Manager Object Mrecyclerview.setlayoutmanager (LayoutManager) for Recyclerview;        Create a list item Split line Object final recyclerview.itemdecoration itemdecoration = new Sampledivider (this);        The Recyclerview control specifies the split line object Mrecyclerview.additemdecoration (itemdecoration);        Create Samplerecycleradapter final Samplerecycleadapter samplerecycleadapter = new Samplerecycleadapter ();        Specifies the adapter mrecyclerview.setadapter (Samplerecycleadapter) for the Recyclerview control;        Set item Add, remove animation mrecyclerview.setitemanimator (new Defaultitemanimator ()); Add Click event Maddbtn.setonclicklistener (New View.onclicklistener () {@Override public void for the lower right corner button OnClick (View v) {//Gets the position of the first visible list item, plus 2 positions, in order to demonstrate the convenience of int positiontoadd = Layoutmanager.findfirs        Tcompletelyvisibleitemposition () + 2;        Insert a new list item after the position Samplerecycleadapter.additem (Positiontoadd);        }        }); Add Click event Mdeletebar.setonclicklistener (New View.onclicklistener () {@Override Public to the delete panel at the top void OnClick (View v) {//Gets the position of the first visible list item, plus 2 positions, in order to demonstrate the convenience of int positiontoremove = LayoutManager.                Findfirstcompletelyvisibleitemposition () + 2;                Deletes the first visible list item samplerecycleadapter.removedata (Positiontoremove);            Hide Delete panel Hidedeletebar () after delete is complete;        }        }); Set Scroll event Mrecyclerview.setonscrolllistener (new Recyclerview.onscrolllistener () {//scroll state change for Recyclerview control                The method of the event @Override public void onscrollstatechanged (Recyclerview recyclerview, int newstate) {            Super.onscrollstatechanged (Recyclerview, newstate); }//Scrolling event method (judging up or down or left and right scrolling) @Override public void onscrolled (recyClerview recyclerview, int dx, int dy) {//If the list is displayed vertically, dy>0 means scrolling up, otherwise it means scrolling down//If the list is displayed horizontally, DX > 0 means scroll to the right, otherwise it means scroll left if (Dy > 0) {//scroll up, hide delete panel, if (Mdelet                    Ebar.getvisibility () = = view.visible) {Hidedeletebar (); }} else {//Scroll down, display panel if (mdeletebar.getvisibility () = = View.gone                    ) {Showdeletebar ();    }                }            }        }); /** * Displays the delete bar, using the animation effect */private void Showdeletebar () {mdeletebar.startanimation (Animationutils.loada        Nimation (this, r.anim.translate_show));    Mdeletebar.setvisibility (view.visible); }/** * Hide Delete bar, use animation effect */private void Hidedeletebar () {mdeletebar.startanimation (Animationutils.loada        Nimation (this, r.anim.translate_hide));    Mdeletebar.setvisibility (View.gone); }}

The Main_activity.xml file is as follows:
<?xml version= "1.0" encoding= "Utf-8"? ><relativelayout xmlns:android= "http://schemas.android.com/apk/res/ Android "xmlns:tools=" http://schemas.android.com/tools "Xmlns:app =" Http://schemas.android.com/apk/res-auto "Android Oid:layout_width= "Match_parent" android:layout_height= "Match_parent" tools:context= " Com.world.hello.recycleview.MainActivity "> <button android:id=" @+id/delete_btn "Android:layout_widt        H= "Match_parent" android:layout_height= "40DP" android:text= "Delete a" android:background= "#4400ffee"        Android:textsize= "14DP"/> <android.support.v7.widget.recyclerview android:id= "@+id/recycler_view" Android:layout_width= "Match_parent" android:layout_height= "match_parent"/> <android.support.design.widge T.floatingactionbutton android:id= "@+id/add_item" android:layout_width= "Wrap_content" Android:layout_ height= "Wrap_content" app:borderwidth= "0DP" App:ripPlecolor= "#eeff0000" android:src= "@android:d rawable/ic_input_add" android:layout_alignparentbottom= "true" Android:layout_alignparentright= "true" android:layout_alignparentend= "true" android:layout_marginright= "33DP" android:layout_marginend= "33DP" android:layout_marginbottom= "38DP"/></relativelayout>

The List_item.xml file is as follows:
<?xml version= "1.0" encoding= "Utf-8"? ><linearlayout xmlns:android= "http://schemas.android.com/apk/res/ Android "    android:layout_width=" match_parent "    android:layout_height=" 40DP "    android:gravity=" Center_ Vertical "    android:orientation=" vertical ">    <textview        android:id=" @+id/text_view "        android: Layout_width= "Match_parent"        android:layout_height= "match_parent"        android:gravity= "center_vertical"        android:textcolor= "@android: Color/black"        android:textsize= "16SP"/></linearlayout>

As follows:



Click the open link to download demo, free points
Next article, will be explained in detail. An example of how to use the Recycleview, animation, and CardView combination!

        

Use of Recyclerview (Android Development Essentials, replace ListView)

Related Article

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.