Android Latest Component Recyclerview, alternative listview

Source: Internet
Author: User

Reprint Please specify source:http://blog.csdn.net/allen315410/article/details/40379159

The latest version of Android 5.0 has been released recently, and for those of me who are not cold on new things, nature will also be concerned, in addition to the new UI design and user experience brought by the new android5.0, the most interesting for Android programmers is the 5.0 version of the SDK and a whole bunch of new APS I. 5.0 is said to add or modify 5,000 API, add some new components, the following recyclerview is one of them, some people say that Google designed to replace the Recyclerview has been commonly used in the ListView, so in this case, We have no reason not to look at the "legend" of how the Recyclerview is used.

Recyclerview Introduction

The Recyclerview widget is a more advanced flexible version of the ListView. This gadget is a container for display that can be very effective in maintaining a limited number of views, scrolling large data sets. Using Recyclerview when you have a collection of data, its elements change the widgets at run time based on user behavior and network events.
The Recyclerview class simplifies, providing the display and processing of large data sets:
Locating the Project layout Manager
The default animation is a common item action, such as deleting or adding items
You can also customize the layout manager and animate the flexibility of recyclerview widgets.


To use the Recyclerview widget, you must specify an adapter and a layout manager. To create an adapter, extend the Recyclerview.adapter class. The details of the implementation depend on the specifics of your data set and the type of opinion. For more information, see the example below.
Layout Manager A's internal location of the project comments Recyclerview and determines when to reuse the project's view is no longer visible to the user. To reuse (or recycle) a diagram, the layout manager may ask the adapter to replace the contents of the view with a different element of the dataset. The idea of recycling in this way improves by avoiding the need to generate unnecessary views or performing lookups of expensive performance Findviewbyid ().
Recyclerview provides these built-in layout managers:
Linearlayoutmanager is displayed in a vertical or horizontal scrolling list item.
Gridlayoutmanager items that appear in the grid.
Staggeredgridlayoutmanager displays staggered grid items.
To create a custom layout manager, extend the Recyclerview.layoutmanager class.
Animation
Add and remove animations from Recyclerview that are enabled by default in the project. To customize these animations, extend the Recyclerview.itemanimator class and use the Recyclerview.setitemanimator () method.

The above content from the official Google document translation, translation is more jerky (my english level, ah ~ ~ against their own line), the following directly on the previous demo to see the specific usage.


The use of Recyclerview

Here is a brief introduction to make a small demo, to step-by-step analysis of the use of Recyclerview. First of all, Recyclerview is the component provided under the ANDROID.SUPPORT.V7 package, so when you need to use Recyclerview, you need to download this package, because I have upgraded the SDK to the latest version--api21, so it is easy to/sdk/ Extras/android/support/v7/appcompat/libs directory to find this jar and source code, it is recommended to upgrade the SDK first, then do! Really do not want to do the download, click the link below the download source code, the source has Recyclerview jar package.

Main interface layout, 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 " >    <android.support.v7.widget.recyclerview        android:id= "@+id/recyclerview"        android:layout_ Width= "Match_parent"        android:layout_height= "80DP"        android:layout_centervertical= "true"        Android: Background= "@android: color/transparent"        android:scrollbars= "None"/></relativelayout>
Item layout, Item_recyclerview.xml

<?xml version= "1.0" encoding= "Utf-8"? ><relativelayout xmlns:android= "http://schemas.android.com/apk/res/ Android "    android:layout_width=" 120DP "    android:layout_height=" 120DP ">    <imageview        android: Id= "@+id/iv_image"        android:layout_width= "80DP"        android:layout_height= "80DP"        android:layout_ Alignparenttop= "true"        android:layout_centerhorizontal= "true"        android:scaletype= "Centercrop"/></ Relativelayout>
Recyclerview data adapter, Myadapter.java

public class Myadapter extends recyclerview.adapter<myadapter.viewholder> {private int[] mdataset;// Outside the incoming data public static class Viewholder extends Recyclerview.viewholder {ImageView mimageview;//TODO auto-generated Method Stubpublic Viewholder (View v) {super (v);}} Public Myadapter (int[] mdataset) {this.mdataset = Mdataset;} /** * Gets the total number of entries */@Overridepublic int getitemcount () {//TODO auto-generated method Stubreturn mdataset.length;} /** * Create Viewholder */@Overridepublic Viewholder Oncreateviewholder (viewgroup parent, int viewtype) {//TODO auto-generate D method Stubview v = layoutinflater.from (Parent.getcontext ()). Inflate (R.layout.item_recycleview, parent, false); Viewholder holder = new Viewholder (v); Holder.mimageview = (ImageView) V.findviewbyid (r.id.iv_image); return holder;} /** * Bind data to Viewholder */@Overridepublic void Onbindviewholder (viewholder holder, int position) {//TODO auto-generated m Ethod Stubholder.mImageView.setImageResource (Mdataset[position]);}}
As you can see from the above, the data adapter has changed a lot with the Baseadapter on the ListView. First the data adapter needs to inherit the Recyclerview.adapter<vh> class, which is a generic class, the generic type is also Viewholder, this viewholder is undoubtedly the implementation of component reuse, Google has helped us to define, In the Recyclerview is an internal class, but the implementation is still thrown to the Android app developers to implement, need to build an internal class in the adapter class, and inherit the Recyclerview,viewholder, Within this inner class, define all the components that need to be reused on the item layout, and finally pass the inner class as a generic to the recyclerview.adapter<vh&gt, and implement the 3 methods that require replication:

GetItemCount () Gets the total number of item.

Oncreateviewholder (viewgroup parent, int viewtype) creates viewholder.

Onbindviewholder (viewholder holder, int position) binds data to Viewholder.

Comparison with ListView data matching

In the ListView there is a GetView () method to return the view is the layout of item, then the layout of this recyclerview item is controlled? In fact, Recyclerview to Viewholder also carried out a certain package, The Viewholder we create must inherit Recyclerview.viewholder, and this recyclerview.viewholder must be constructed with a view that is equivalent to the GetView of our ListView ( Convertview (i.e., we need to inflate the item layout needs to be passed in).

Also, in the ListView, the Convertview is reused, in Recyclerview, the Viewholder is used as the unit of the cache, and then Convertview as the Viewholder member variable remains in Viewholder , that is, assuming that there are no screens showing 10 entries, 10 Viewholder are created and cached, and each is reused with viewholder, so he turns the GetView method into a oncreateviewholder.

Finally, use this recyclerview,mainactivity.java in the activity.

public class Mainactivity extends Activity {/** Recyclerview object */private recyclerview recyclerview;/** picture resource */private int[] mDataset;/ * * Data adapter */private myadapter madapter; @Overrideprotected void OnCreate (Bundle savedinstancestate) {super.oncreate ( Savedinstancestate); Setcontentview (r.layout.activity_main); Recyclerview = (Recyclerview) findViewById ( R.id.recyclerview);//Initialize picture data Mdataset = new int[] {r.drawable.a, r.drawable.b,//r.drawable.c, R.DRAWABLE.D, R.drawable . E,//r.drawable.f, r.drawable.g, r.drawable.h, r.drawable.i};//set layout manager Linearlayoutmanager Linearlayoutmanager = new Linearlayoutmanager (this); Linearlayoutmanager.setorientation (linearlayoutmanager.horizontal); Recyclerview.setlayoutmanager (Linearlayoutmanager);//Set Adapter Madapter = new Myadapter (mdataset); Recyclerview.setadapter (Madapter);}} 

In mainactivity using Recyclerview as simple as using a ListView, the only difference is that you need to set a layout manager for Recyclerview, Google provides us with 3 different layout management (see the top introduction for details), where I use the Linearlayoutmanager, and set the layout to show horizontally. Well, the basic usage of recyclerview is over, and the other two layout managers about Recyclerview are not going to talk about it for the time being. Here is the run



Set event callbacks for Recyclerview

When using the Recyclerview component, a "bitter" problem was found: Recyclerview did not click on the item's event listener settings, similar to the one at least a Setonitemclicklistener method in the ListView, Used to listen for item clicks and make corresponding logical processing. But through the Recyclerview API, did not find this or similar to the function of the method available, which has to be said to be a "tragedy", also heard that this is to replace the ListView, it does not seem to be so, please google to explain Ah!

Well, Google should not be explained in the near future, but we have to find a way to solve this problem, is to add a callback function for Recyclerview, this is not difficult! Really can't understand, can look at my previous blog post, Android custom components--imitation iOS sliding button, there are some related usage. Here is the callback function I added in adapter.

public class Myadapter extends recyclerview.adapter<myadapter.viewholder> {private int[] mdataset;//Outside Incoming data/** * The callback interface for item * */public interface Onitemclicklistener {void Onitemclicklistener (view view, int position);} Private Onitemclicklistener listener; Click on the item's callback object/** * Set Callback listener * * @param listener */public void Setonitemclicklistener (Onitemclicklistener listener) {THIS.L Istener = listener;} public static class Viewholder extends Recyclerview.viewholder {ImageView mimageview;//TODO auto-generated method Stubpu Blic Viewholder (View v) {super (v);}} Public Myadapter (int[] mdataset) {this.mdataset = Mdataset;} /** * Gets the total number of entries */@Overridepublic int getitemcount () {//TODO auto-generated method Stubreturn mdataset.length;} /** * Create Viewholder */@Overridepublic Viewholder Oncreateviewholder (viewgroup parent, int viewtype) {//TODO auto-generate D method Stubview v = layoutinflater.from (Parent.getcontext ()). Inflate (R.layout.item_recycleview, parent, false); Viewholder holder = new ViewholdeR (v); Holder.mimageview = (ImageView) V.findviewbyid (r.id.iv_image); return holder;} /** * Bind data to Viewholder */@Overridepublic void Onbindviewholder (Viewholder holder, final int position) {//TODO Auto-gener Ated method Stubholder.mImageView.setImageResource (Mdataset[position]); if (listener! = null) { Holder.mImageView.setOnClickListener (New Onclicklistener () {@Overridepublic void OnClick (View v) { Listener.onitemclicklistener (v, Position);}});}}
First, define an internal interface in adapter, define the callback function inside the interface, then expose a method to set the interface object, set the object of the internal interface through this method, and finally pass the related information through the interface object in the method of Viewholder binding data. Here's how to set up this listener in mainactivity:

Madapter.setonitemclicklistener (New Onitemclicklistener () {@Overridepublic void Onitemclicklistener (view view, int Position) {//TODO auto-generated method Stubtoast.maketext (mainactivity.this, Position + "", Toast.length_short). Show ( );}});
Here's how to run:


Please download the source code here



Android Latest Component Recyclerview, alternative 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.