Android Latest Component Recyclerview, alternative listview

Source: Internet
Author: User

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

The latest 5.0 version of Android, which has been officially announced recently, will naturally be of concern to those of me who are not cold on new things, and in addition to the new UI design and user experience brought by the new android5.0, the most interesting of the Android program Ape is the 5.0 version of the SDK and a whole bunch of new Api. 5.0 is said to add or change the additional 5,000 API, new components, the following recyclerview is one of them, some people say that Google designed to replace the Recyclerview is always used in the ListView, So that being the case, we have no reason not to look at how this "legend" of Recyclerview is used.

Recyclerview Brief Introduction

The Recyclerview widget is a more advanced flexible version of the ListView. This gadget is a container that can be used to display, effectively maintaining a limited number of views, scrolling large data sets. Using Recyclerview when you have a collection of data, its elements are executed to change widgets 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 an item
You can also recyclerview parts in the flexibility of your own defined layout manager and animations.


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 details of your data set and the type of opinion. For a number of other information, please refer to the scale 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 such a way improves by avoiding the need to generate unnecessary views or running expensive performance Findviewbyid () lookups.
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 your own definition layout manager, extend the Recyclerview.layoutmanager class.
Animation
Animations are added and deleted by default in the project Recyclerview enabled. To define these animations yourself, 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 demo to see the detailed use of the method.


How to use Recyclerview

The following introduction to make a small demo, to step-by-step analysis of how recyclerview use. First of all, Recyclerview is the component provided under the ANDROID.SUPPORT.V7 package, so it is necessary to download this package if I need to use Recyclerview, because I have upgraded the SDK to the latest version number--API21, so very easy to Sdk/extras/android/support/v7/appcompat/libs folder to find this jar and source code, it is recommended to upgrade the SDK first, then do it! Really do not want to do the download, click on the link below the blog to download the source code, the source code 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]);}}
It can be seen from above that the data adapter has changed very much compared to the baseadapter used by 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 define, In the Recyclerview is an internal class, but the detailed implementation or throw to the Android app developers to implement, need to build an internal class in the adapter class, and inherit 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 need to be replicated:

GetItemCount () Gets the total number of item.

Oncreateviewholder (viewgroup parent, int viewtype) creates viewholder.

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

Control to fit the ListView data

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 this is the case, 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).

Another point, the ListView Convertview is multiplexed, in Recyclerview, is the Viewholder as the unit of the cache, and then Convertview as the Viewholder member variable remains in Viewholder, That is, if there is no screen to display 10 entries, then 10 Viewholder will be created to cache, each time the reuse is Viewholder, so he turned getview this method into 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 above for a brief introduction), where I use the Linearlayoutmanager, and set the layout to show horizontally. OK, about the basic use of the Recyclerview, the other two layout manager about Recyclerview the temporary not to say, very similar. The following is the execution



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 the recyclerview of the API, have not found this or similar to the function of the method available, which has to be said to be a "tragedy", but also heard that this is to replace the ListView, it seems not this, please google to explain Ah!

Well, Google should not be able to explain recently, but we have to find a way to solve the 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 own definition components--imitation iOS sliding button, there are some related to how to use. Here are the callback functions 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 is the execution:


Please download the source code here



Android Latest Component Recyclerview, alternative listview

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.