[Android] A simple example of Recyclerview

Source: Internet
Author: User
Tags recyclerview android

Last year Google's IO showed a new ListView, which is Recyclerview.

Here is the official note, my English ability is limited, but I probably understand that: Recyclerview will be more scalable than the ListView, use more efficient, and more flexible, how specific, after a year, we also found that it is more and more powerful, so it is necessary to meet this small partner.

The widget is a more advanced and RecyclerView flexible version of ListView . This widget was a container for displaying large data sets so can be scrolled very efficiently by maintaining a limited n Umber of views. Use the widget when you have RecyclerView data collections whose elements change at runtime based on user action or network events .

The RecyclerView class simplifies the display and handling of large data sets by providing:

    • Layout Managers for positioning items
    • Default animations for common item operations, such as removal or addition of items

You also has the flexibility to define custom layout managers and animations for RecyclerView widgets.


We can find this gadget on the latest version of SUPPORT-V7, this article found this jar on V21: sdk\extras\android\m2repository\com\android\support\ recyclerview-v7\21.0.0, in the directory will Recyclerview-v7-21.0.0.aar decompression, take out Classes.jar, You can change the name to: Android-support-v7-recyclerview.jar, at least I did.

All right, get into the demo theme.

1.demo structure

2. Example


3. Let's look at the code side, this control, first introduce this component in the interface layout file:

Activity_main.xml

<relativelayout xmlns:android= "http://schemas.android.com/apk/res/android" xmlns:tools= "http// Schemas.android.com/tools "android:layout_width=" match_parent "android:layout_height=" Match_parent "Tools:context = "${relativepackage}.${activityclass}" > <linearlayout android:layout_width= "fill_parent" android:l ayout_height= "fill_parent" android:orientation= "vertical" > <radiogroup Android:layout_widt            H= "Fill_parent" android:layout_height= "wrap_content" android:checkedbutton= "@+id/linearlayout_rb"                Android:gravity= "Center_horizontal" android:orientation= "Horizontal" > <radiobutton Android:id= "@+id/linearlayout_rb" android:layout_width= "Wrap_content" Android:                layout_height= "Wrap_content" android:text= "@string/linearlayout"/> <radiobutton        Android:id= "@+id/gridlayout_rb"        Android:layout_width= "Wrap_content" android:layout_height= "Wrap_content" Android:tex t= "@string/gridlayout"/> </radiogroup><span style= "White-space:pre" ></span> <androi            D.support.v7.widget.recyclerview android:id= "@+id/recyclerview" android:scrollbars= "vertical" Android:layout_width= "Match_parent" android:layout_height= "match_parent"/> </linearlayout>&lt ;/relativelayout>

4. Here is how to use it, here is a simple way to use, in the code I have added a note, a simple understanding of it.

Mainactivity.java

Package Org.jan.components.demo;import Java.util.arraylist;import Org.jan.components.demo.customadapter.onitempressedlistener;import Android.app.activity;import Android.os.Bundle ; Import Android.support.v7.widget.defaultitemanimator;import Android.support.v7.widget.gridlayoutmanager;import Android.support.v7.widget.linearlayoutmanager;import Android.support.v7.widget.recyclerview;import Android.support.v7.widget.recyclerview.recyclerlistener;import Android.support.v7.widget.recyclerview.viewholder;import Android.util.log;import Android.view.View;import Android.view.view.onclicklistener;import Android.widget.radiobutton;import android.widget.toast;/** * Android Recyclerview Simple Instance Code * @author Jan */public class Mainactivity extends Activity {private static final String TAG = "Mainact Ivity ";p rivate static final String Key_layout_manager =" LayoutManager ";p rivate enum Layoutmanagertype {grid_layout_ MANAGER, linear_layout_manager}private RadioButton mlinearlayoutbutton;private RadioButton mGrIdlayoutbutton;private recyclerview mrecyclerview;private customadapter madapter;private RecyclerView.LayoutManager Mlayoutmanager;private Layoutmanagertype mcurrentlayoutmanagertype;//Set up the simulation data private arraylist<string> mdatalist;//the number of set columns in a grid layout private static int spancount=3;//The number of analog data private static int datasize = n; @Overrideprotected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate); Setcontentview (R.layout.activity_main); Initdatas (); Initviews (savedinstancestate);} private void Initviews (Bundle savedinstancestate) {Mlinearlayoutbutton = (RadioButton) Findviewbyid (r.id.linearlayout _RB); Mlinearlayoutbutton.setonclicklistener (new Onclicklistener () {@Overridepublic void OnClick (View v) { Setrecyclerviewmanagertype (Layoutmanagertype.linear_layout_manager);}}); Mgridlayoutbutton = (RadioButton) Findviewbyid (R.ID.GRIDLAYOUT_RB); Mgridlayoutbutton.setonclicklistener (new Onclicklistener () {@Overridepublic void OnClick (View v) {Setrecyclerviewmanagertype (LayoutmanagertypE.grid_layout_manager);}); Mcurrentlayoutmanagertype = Layoutmanagertype.linear_layout_manager;if (savedinstancestate!=null) { Mcurrentlayoutmanagertype = (layoutmanagertype) savedinstancestate. getserializable (KEY_LAYOUT_MANAGER) ; LOG.I (TAG, "mcurrentlayoutmanagertype=" +mcurrentlayoutmanagertype);} Mrecyclerview = (Recyclerview) Findviewbyid (R.id.recyclerview); Setrecyclerviewmanagertype ( Mcurrentlayoutmanagertype) Madapter = new Customadapter (mdatalist); Mrecyclerview.setadapter (mAdapter);// Set the recycler to have a fixed size, improve the display efficiency mrecyclerview.sethasfixedsize (TRUE);//Set the default animation, the removal and add the effect of the show, now on GitHub can find a lot of expansion, Interested can look for Mrecyclerview.setitemanimator (New Defaultitemanimator ());//Implement our method of listening to adapter, Because Recyclerview does not have a ListView and Onlongclick similar method Madapter.setonitempressedlistener (new Onitempressedlistener () { @Overridepublic void Onitemclick (int position) {Toast.maketext (Mainactivity.this, "You clicked Item-" +mdatalist.get ( Position), Toast.length_short). Show ();} @Overridepublic boolean Onitemlongclick (int Position) {//Here simulates the deletion of the function removeitembyposition (position);//insertitembyposition (position); Toast.maketext (Mainactivity.this, "You long pressed item-" +mdatalist.get (position), Toast.length_short). Show (); return true;}); Mrecyclerview.setrecyclerlistener (New Recyclerlistener () {//resource is reclaimed after being called @overridepublic void onviewrecycled (ViewHolder Viewholder) {Customadapter.viewholder VH = (org.jan.components.demo.CustomAdapter.ViewHolder) Viewholder; LOG.D (TAG, "onviewrecycled->" +vh.getitemtext (). GetText ());});} Create the simulated data private void Initdatas () {mdatalist = new arraylist<string> (); for (int i = 0; i < datasize; i++) {Mdatal Ist.add (String.Format (getString (r.string.iamstudent), i));}} /** * Can change the layout display method of Recycler * @param type */protected void Setrecyclerviewmanagertype (Layoutmanagertype type) {int Scrollpo Sition = 0;if (Mrecyclerview.getlayoutmanager () = null) {scrollposition = ((Linearlayoutmanager) Mrecyclerview.getlayoutmanager ()). Findfirstcompletelyvisibleitemposition ();} Switch (type) {//Mesh case Grid_layouT_manager:mlayoutmanager = new Gridlayoutmanager (this, spancount); mcurrentlayoutmanagertype = LayoutManagerType.GRID _layout_manager;break;//linear, such as listcase Linear_layout_manager:mlayoutmanager = new Linearlayoutmanager (this); Mlayoutmanager.canscrollhorizontally (); mcurrentlayoutmanagertype = Layoutmanagertype.linear_layout_manager;break ;d Efault:mlayoutmanager = new Linearlayoutmanager (this); Mcurrentlayoutmanagertype = Layoutmanagertype.linear_layout _manager;break;} Mrecyclerview.setlayoutmanager (Mlayoutmanager); mrecyclerview.scrolltoposition (scrollposition);} /** * Removes data from the specified position by Recyclerview adapter * @param position */protected void removeitembyposition (int position) {if ( madapter!=null&&position>0) {madapter.notifyitemremoved (position); Mdatalist.remove (position); Madapter.notifyitemrangechanged (position, Madapter.getitemcount ());//If you use this, there is no animation effect. Madapter.notifydatasetchanged ();}} Corresponding to this is the protected void insertitembyposition (int position) {if (madapter!=null&&position) that can be added to the specified index.>0) {madapter.notifyiteminserted (position); Mdatalist.add (position, String.Format (getString ( r.string.iamstudent) (position)); Madapter.notifyitemrangechanged (position, Madapter.getitemcount ());}} @Overrideprotected void Onsaveinstancestate (Bundle outstate) {outstate.putserializable (Key_layout_manager, Mcurrentlayoutmanagertype); super.onsaveinstancestate (outstate);} @Overrideprotected void Onrestoreinstancestate (Bundle savedinstancestate) {super.onrestoreinstancestate ( savedinstancestate);}}
5. This customadapter is the realization of recyclerview.adapter, of which Viewholder seems to be to us to define, I have not read the source code, but my intuition tells me that he must be optimized for the ListView of the Viewholder re-use.

Package Org.jan.components.demo;import Java.util.list;import Android.support.v7.widget.recyclerview;import Android.view.layoutinflater;import Android.view.view;import Android.view.view.onclicklistener;import Android.view.view.onlongclicklistener;import Android.view.viewgroup;import Android.widget.imageview;import Android.widget.textview;public class Customadapter Extendsrecyclerview.adapter<customadapter.viewholder> { Private list<string> datalist;private onitempressedlistener onitempressedlistener;public CustomAdapter (List <String> data) {this.datalist = data;} @Overridepublic int GetItemCount () {return datalist.size ();} Replace the contents in the View @overridepublic void Onbindviewholder (viewholder viewholder, int position) {Viewholder.getdrawableid (). Setbackgroundresource (r.drawable.school_student); Viewholder.getitemtext (). SetText (Datalist.get (position));} The layout manager of Recyclerview generates a new viewholder@overridepublic Viewholder Oncreateviewholder (ViewGroup viewgroup, int viewtype) {View V= Layoutinflater.from (Viewgroup.getcontext ()). Inflate (R.layout.layout_row_item, ViewGroup, false); return new Viewholder (v);} /** * Inherit Recyclerview viewholder to customize Viewholder */public class Viewholder extends Recyclerview.viewholder in a view {private ImageView drawableid;private TextView itemtext;public viewholder (View itemview) {super (Itemview); if (itemview!=null) { Here I added a tap and long press event for this view, in order to make this demo more like a Listviewitemview.setonclicklistener (new Onclicklistener () {@ overridepublic void OnClick (View v) {if (onitempressedlistener!=null) {Onitempressedlistener.onitemclick (getPosition ());}}}); Itemview.setonlongclicklistener (New Onlongclicklistener () {@Overridepublic Boolean onlongclick (View v) {if ( Onitempressedlistener!=null) {return Onitempressedlistener.onitemlongclick (getPosition ());} return false;}}); Drawableid = (ImageView) Itemview.findviewbyid (r.id.item_image); itemtext = (TextView) Itemview.findviewbyid ( R.id.item_text);}} Public ImageView Getdrawableid () {return drawableid;} Public TextView GetitemteXT () {return itemtext;}} public void Setonitempressedlistener (Onitempressedlistener onitempressedlistener) {This.onitempressedlistener = Onitempressedlistener;} Protected static interface onitempressedlistener{void Onitemclick (int position); Boolean onitemlongclick (int position) ;}}
Well, the code is very clear and concise, mainly in order to increase the understanding of Recyclerview, now a lot of new apps, have been added to this component, many Daniel also wrote about his strong expansion.

I've also added an advanced post here that you and I have time to learn

Android Recyclerview Art-like controls with full parsing experience

[Android] using Recyclerview instead of ListView (ii)

Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

[Android] A simple example of Recyclerview

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.