Go Preliminary study on Recyclerview

Source: Internet
Author: User

Original address: http://www.grokkingandroid.com/first-glance-androids-recyclerview/
Recyclerview was released last year at the Google I/O conference with the Android L Preview, and the next few translations will be a comprehensive introduction to Recyclerview from all aspects:

This article sample code project address: Https://github.com/writtmeyer/recyclerviewdemo

Why is it called Recyclerview?

This is what Google describes in the Android L Preview API documentation:
a very flexible control for displaying large amounts of data within a limited window range.
So Recyclerview is suitable for situations where there is a large number of similar view but cannot be displayed simultaneously on the screen, such as contacts, user lists, music file lists, etc. To see more information you need to scroll to try and recycle and reuse The view that leaves the screen.

This process is explained in slices: the left side is the initial state of the application, and when scrolling up the view, some sub view is ready to be recycled, such as two invisible views in the red-framed part on the right. Now the collector can put them in a list of view that is ready to be reused for reuse at the right time.

Recycling of view is useful because it saves CPU resources without having to repopulate the layout each time, and saves memory resources because it does not save a large number of invisible views.

As you can see here, this concept has long been available, and the ListView is using such a mechanism. Yes, but in the ListView, the appearance of the control, the recycling process, and other operations are tightly coupled and inflexible, which is why Google has to develop recyclerview to replace its meaning.

Recyclerview itself does not care about view-related issues

Due to the tight coupling problem of the ListView, Google's improvement is that Recyclerview itself does not participate in any view-related issues. It doesn't care how to put the sub-view in the right place, or how to split the sub-view, less about the appearance of each child view. Further, Recyclerview is only responsible for the recycling and reuse of the work, which is the origin of its name.

All questions about layout, drawing, and other related issues, which are related to data presentation, are delegated to some "plug-in" classes to handle. This makes the Recyclerview API very flexible. Do you need a new layout? Access to another LayoutManager! Do you want a different animation? Access to a new itemanimator, and so forth.

The following are some of the important classes used in Recyclerview for data presentation, all of which are internal classes of Recyclerview:

    • Adapter: Wraps the data collection and creates a view for each entry.
    • Viewholder: Saves the child view that is used to display each data entry.
    • LayoutManager: Place the view of each entry in the appropriate location.
    • Itemdecoration: Draws some decorative views around or above the view of each entry.
    • Itemanimator: Adds an animation effect when an entry is added, removed, or reordered.

These classes are described separately below:

Recyclerview.viewholder

Viewholder's basic role is to cache the View object, Android official early money recommended to use the Viewholder programming mode, but now use this mode will be mandatory.

Recyclerview.viewholder subclasses can access the root view of each entry through the member variable itemview of the Viewholder public, so there is no need to save this view in the Viewholder subclass.

The following is an example code for Viewholder:

public final static class ListItemViewHolder extends RecyclerView.ViewHolder { TextView label; TextView dateTime; public ListItemViewHolder(View itemView) { super(itemView); label = (TextView)itemView.findViewById(R.id.txt_label_item); dateTime = (TextView)itemView.findViewById(R.id.txt_date_time); }}
Recyclerview.adapter

Adapter acts as two roles: Access the data collection and is responsible for creating the correct view for each entry. Adapter often appear in Android, such as ListView, Autocompletetextview, Spinner, and so on, they all inherit from Adapterview, but Recyclerview did not do so.

For Recyclerview, Google decided to replace the old adapter interface with the new Recyclerview.adapter base class. So, Simplecursoradapter and Arrayadapter are all going to be history, or at least not the way they are being used.

Currently Recyclerview.adapter is not implemented by default and may be added later. Since Recyclerview.adapter is an abstract class, the following three methods must be implemented:

    • Public VH Oncreateviewholder (viewgroup parent, int viewtype)
    • public void Onbindviewholder (VH holder, int position)
    • public int GetItemCount ()

Where VH is a generic class that needs to be replaced with a specific class when inheriting recyclerview.adapter. The sample code for adapter is as follows:

PublicClassRecyclerviewdemoadapterExtendsRecyclerview.Adapter <Recyclerviewdemoadapter.listitemviewholder> {Private list<demomodel> items; Recyclerviewdemoadapter (list<demomodel> modeldata) {if (Modeldata = =NULL) {ThrowNew IllegalArgumentException ("Modeldata must not being null"); }This.items = Modeldata; } @OverridePublic Listitemviewholder Oncreateviewholder (ViewGroup viewgroup,int viewtype) {View Itemview = Layoutinflater. From (Viewgroup.getcontext ()). Inflate (r.layout.item_demo_01, ViewGroup,FALSE);ReturnNew Listitemviewholder (Itemview); } @OverridePublicvoid Onbindviewholder (Listitemviewholder viewholder,int position) {Demomodel model = Items.get (position); ViewHolder.label.setText (Model.label); String datestr = Dateutils.formatdatetime (ViewHolder.label.getContext (), Model.dateTime.getTime (), Dateutils.format _abbrev_all); ViewHolder.dateTime.setText (DATESTR); } @Override public int GetItemCount () { return items.size ();} public Final static class Listitemviewholder extends recyclerview.  Viewholder { //... shown above in the Viewholder section}} /c2> 
Recyclerview.layoutmanager

LayoutManager is probably the most interesting part of Recyclerview, which is responsible for placing all of the sub-view into place. The class has a default implementation: Linearlayoutmanager, which can be used when you want to implement a horizontal or vertical list.

You must set a LayoutManager for Recyclerview, or you will throw an exception:

18L0105:00:00.00024532453 E AndroidRuntime:java.lang.NullPointerException:AttemptTo invokeVirtualmethod ' void android.support. v7. widget. recyclerview$layoutmanager. Onmeasureon a Span class= "Hljs-title" >null object reference08-01 05:00:00.000 2453 2453 E androidruntime:at android.support.v7.widget.RecyclerView.onMeasure (Recyclerview.java: 1310)             

Currently LayoutManager has only one abstract method:

    • Public Layoutparams Generatedefaultlayoutparams ()

      But there is one more way to rewrite it, because this method will soon become abstract:

public void scrollToPosition(int position) {            if (DEBUG) { Log.e(TAG, "You MUST implement scrollToPosition. It will soon become abstract"); } }

However, it is not enough to rewrite the above two methods, after all, the responsibility of LayoutManager is to put all the sub-view to the appropriate position, so you also need to rewrite the Onlayoutchildren () method:

public void onLayoutChildren(Recycler recycler, State state) {            Log.e(TAG, "You must override onLayoutChildren(Recycler recycler, State state) ");        }
Linearlayoutmanager

Linearlayoutmanager is currently the only default implementation of LayoutManager, which can be used to create horizontal or vertical lists.

LinearLayout is very complex, here are just a few of the key parts. The usage of Linearlayoutmanager is very simple: Initialize it, then set a direction (horizontal/vertical) on it:

LinearLayoutManager layoutManager = new LinearLayoutManager(context);layoutManager.setOrientation(LinearLayoutManager.VERTICAL);layoutManager.scrollToPosition(currPos);recyclerView.setLayoutManager(layoutManager);

Linearlayoutmanager also provides methods to find the first and last entries on the current screen:

    • Findfirstvisibleitemposition ()
    • Findfirstcompletelyvisibleitemposition ()
    • Findlastvisibleitemposition ()
    • Findlastcompletelyvisibleitemposition ()
Recyclerview.itemdecoration

Using Itemdecoration, you can add offsets to each entry, add spacing between entries, highlight entries, add other modifiers, and more.
Itemdecoration is not required, for example, you can use CardView as a view for each entry.

In addition, any number of Itemdecoration,recyclerview can be added to traverse all itemdecoration and then invoke each of the drawing methods in the appropriate order

The Itemdecoration virtual base class consists of the following three methods:

    • public void OnDraw (Canvas C, recyclerview parent)
    • public void Ondrawover (Canvas C, recyclerview parent)
    • public void Getitemoffsets (Rect outrect, int itemposition, Recyclerview parent)

The content drawn in OnDraw may be overwritten by the contents of the entry, and the Ondrawover () method is required if you want to draw the content on the entry. If you need entry spacing to draw a split line, there is little difference between using the two methods above, but if you really want to add a decorative effect, you still need to use Ondrawover ().

LayoutManager calls the Getitemoffset () method during the measurement phase to correctly calculate the size of each bar view. Outrect parameters may seem strange at first glance, why not use a return value? However, such parameter settings do make sense, making it possible to reuse the same Rect object for all child views Recyclerview, saving resource overhead. It's not necessary, but it's really efficient.

Recyclerview.itemanimator

Itemanimator can animate each entry, and it handles the following three types of events mainly:

    • An item gets added to the data set
    • An item gets removed from the data set
    • An item moves as a result of one or more of the previous-operations

Itemanimator has a default implementation: Defaultitemanimator, if no custom Itemanimator,recyclerview is set, the default defaultitemanimator is used.

Obviously if you want the animation to take effect, you need to know the change in the data set, which requires adapter help. In previous releases, the Notifydatasetchanged () method needed to be called when changes changed. This is inappropriate, however, because this method triggers a redraw for all visual sub-view and has no animated effect. To see an animated effect, you need to use a more specific method:

The Recyclerview.adapter class contains many methods of the notifyxxx () type, and the two most common are:

    • Public final void notifyiteminserted (int position)
    • Public final void notifyitemremoved (int position)
Listener

Recyclerview provides a number of very generic listeners. The usual usage patterns are not available now, Recyclerview does not provide Onitemclicklistener or onitemlongclicklistener. However, you can use Recyclerview.onitemtouchlistener with gesture snooping to handle these events. The required coding work must be done before the same results are achieved.

Combine all the above classes together

Layout file:

<RelativelayoutXmlns: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:paddingleft="@dimen/activity_horizontal_margin"android:paddingright="@dimen/activity_horizontal_margin"android:paddingtop="@dimen/activity_vertical_margin"Android:paddingbottom="@dimen/activity_vertical_margin"tools:context=". Recyclerviewdemoactivity "><Android.support.v7.widget.RecyclerViewAndroid:id="@+id/recyclerview"Android:layout_width="Match_parent"android:layout_height="Match_parent"tools:context=". Mainactivity "tools:listitem="@layout/item_demo_01"/><ImageButtonAndroid:id="@+id/fab_add"android:layout_alignparentright="True"Android:layout_alignparentbottom="True"Android:layout_width= "@dimen/fab_size" android:layout_height=  "@dimen/fab_size" android:layout_gravity=  "bottom|right" android:layout_marginright=  "16DP" android:layout_marginbottom=  "16DP" android:background= "@ Drawable/ripple "android:statelistanimator=" @anim/anim " Span class= "Hljs-attribute" >android:src= "@drawable/ic_action_add" android:elevation= "1DP"/></ RELATIVELAYOUT>            

Recyclerview's attributeset will be used in the Generatelayoutparams () method:

@Overridepublic ViewGroup.LayoutParams generateLayoutParams(AttributeSet attrs) {   if (mLayout == null) { throw new IllegalStateException("RecyclerView has no LayoutManager"); } return mLayout.generateLayoutParams(getContext(), attrs);}

The Program code section is simple:

Setcontentview (r.layout.activity_recyclerview_demo); Recyclerview = (Recyclerview) Findviewbyid (R.id.recyclerView) ; Linearlayoutmanager LayoutManager =New Linearlayoutmanager (this); Layoutmanager.setorientation (linearlayoutmanager.vertical); Layoutmanager.scrolltoposition (0); Recyclerview.setlayoutmanager (LayoutManager);//allowsFor optimizationsIfAll item Views isof the same size:recyclerView.setHasFixedSize (true);//For the SakeOf simplicity I misused the application subclass as a daolist<demomodel> items = Recyclerviewdemoapp.getdemodata (); a Dapter =New Recyclerviewdemoadapter (items); Recyclerview.setadapter (adapter); Recyclerview.itemdecoration itemdecoration =New Divideritemdecoration (this, divideritemdecoration.vertical_list); Recyclerview.additemdecoration ( itemdecoration);//Thisis thedefault;//This call is actually only necessary with Custom Itemanimatorsrecyclerview.setitemanimator (new Defaultitemanimator ());//Onclickdetection is done in This Activity ' s onitemtouchlistener//with the help of a gesturedetector;//Tip by Ian Lake on g+ in a Co Mment to this post://https://plus.google.com/+LucasRocha/posts/ 37u8gwtyxderecyclerview.addonitemtouchlistener (this); gesturedetector = new Gesturedetectorcompat (this, new Recyclerviewdemoongesturelistener ()) ;

The main steps are as follows:

    1. Get a reference to Recyclerview
    2. Create a LayoutManager and add
    3. Create a adapter and add
    4. If necessary, create 1 or more itemdecoration and add
    5. If necessary, create a itemanimator and add
    6. If necessary, create 1 or more listeners and add

Of course this is just the initial code, and the really interesting part is that Recyclerview has a lot of internal classes that can be used to inherit and implement a variety of custom effects, which is where a lot of work really needs to be done.

Go Preliminary study on 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.