Use of the Android V7 Compatibility Pack Recyclerview (ii)

Source: Internet
Author: User

Previous post use of the Android V7 Compatibility Pack Recyclerview (a) the most basic usage of recyclerview, and now start digging into more detailed content.
In the Recyclerview API, there is a sentence

A flexible view for providing a limited window to a large data set.

The idea is that Recyclerview is a flexible view that solves this situation when a large amount of data is displayed on a window of limited size.

From the above description you can see the use of Recyclerview scene. If we have a large number of the same type of data to display on the screen, and at this time it is likely that the entire screen can not fully display all the data, Recyclerview is a suitable choice. When the user scrolls the screen up and down, the recycle of item is also done at the same time, when a new item enters the visual range, an old item must be moved out of the visual range, and the item being removed is recycled. So what does it do to recycle item, in fact, he is a very useful method, because it saves CPU resources and memory.

Maybe you'd say we spent a lot of time with the ListView, what's so special about Recyclerview and the way we used to be, that when we used the ListView, the display, the reuse of the loop, and some of the other things had some degree of coupling, Now Recyclerview offers a more flexible approach.

Google Now uses this method, it does not care about what Recyclerview see, and does not care whether the element is displayed in the right place, but also do not care about how each element is separated. The only thing Recyclerview do is recycling. Hence the name Recyclerview.

Here are a few of the most important classes related to Recyclerview

Adapter: Adapter, bound data set
Viewholder: Saving views based on current data
LayoutManager: Layout manager. Determine how item is placed
Itemdecoration: Barely understood as item adorner, can beautify item
Itemanimator: Animations are animated when an item is added, deleted, or rearranged.

Viewholder

Android has been recommending the use of the Viewholder mode for a long time, because it can greatly improve the efficiency, the interface fluency increases to a certain extent. The Recyclerview adapter is an internal class, and we extend our subclasses by inheriting it, just like this.

public  final  static   class  listitemviewholder  extends  recyclerview . viewholder  { TextView title;   //item interface  TextView description;   //item interface    //of course you can continue to add these elements  public  listitemviewholder  (View Itemview)      {super  (Itemview);      //Association reference  title= (TextView) Itemview.findviewbyid (r.id.title);   description= (TextView) Itemview.findviewbyid (r.id.description); }}
Recyclerview.adapter

The adapter accomplishes two main functions: it is responsible for establishing the connection between the base dataset and the individual item layout. Adapters are one of the important parts of Android. It is used in many places, such as the ListView, Autocompletetextview, and spinner, all using adapters.

Google uses Recyclerview's internal class adapter instead of the traditional adapter, so in Recyclerview you won't see adapters like Simplecursoradapter and Arrayadapter.

Unfortunately, however, Google does not provide the default implementation class for Recyclerview.adapter, which is an abstract class, so we have to implement three methods.

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

VH is a generic that inherits from Viewholder and must provide a specific type in the subclass. The most basic adapter notation is as follows

 Public  class recyclerviewadapter extendsrecyclerview. Adapter <recyclerviewadapter. Itemviewholder> {             Privatelist<demomodel> items; Recyclerviewadapter (list<demomodel> modeldata) {if(Modeldata = =NULL) {Throw NewIllegalArgumentException ("Modeldata must not being null"); } This. Items = Modeldata; }@Override     PublicItemviewholderOncreateviewholder(ViewGroup ViewGroup,intViewType) {View Itemview = Layoutinflater.                From (Viewgroup.getcontext ()). Inflate (R.layout.item,viewgroup,false);return NewItemviewholder (Itemview); }@Override     Public void Onbindviewholder(Itemviewholder Viewholder,intPosition) {Demomodel model = Items.get (position);        ViewHolder.title.setText (Model.gettitle ());    ViewHolder.description.setText (Model.getdescription ()); }@Override     Public int GetItemCount() {returnItems.size (); } Public Final Static  class itemviewholderextends recyclerview. Viewholder {                    //... shown above in the Viewholder section}}
Recyclerview.layoutmanager

Layout Manager is the most interesting place in Recyclerview, it is responsible for the layout of all child item, in the latest V7 compatibility library, it has three implementation classes, respectively Linearlayoutmanager (linear layout), Gridlayoutmanager ( A grid layout), Staggeredgridlayoutmanager (streaming layout), by default, if we do not set the layout manager, a linear layout will be used. We can implement our own layout manager by inheriting this class, we decide how to put the item content, but when you look at the code of the three implementation classes above, you will find that it is not easy to do one thing ... The code is so long ... It's true! The specific use of layout Manager will open another blog, here first introduce the linear layout manager simple use. The code is as follows

//实例化对象new LinearLayoutManager(context);//设置布局方向为竖直layoutManager.setOrientation(LinearLayoutManager.VERTICAL);//滚动到那一项layoutManager.scrollToPosition(currPos);//设置布局管理器recyclerView.setLayoutManager(layoutManager);
Recyclerview.itemdecoration

Let me call it an item adorner, using Itemdecoration we can add offsets to item, add item splitter lines, highlight, and so on. We can add a lot of itemdecoration,recyclerview and go through all the itemdecoration in turn and call the drawing method to complete the decoration. It has three abstract 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 obscured by the contents of the item, but the content you draw in Ondrawover will be drawn above item. We can use offsets to simply split the item, but if you want to display a split line, you have to use the Ondrawover method to explicitly draw a divider line.

The layout manager calls the Getitemoffset method at the measurement stage, and the Outrect parameter looks a bit odd with a rect type parameter, so why not use a return value instead of it, since Google does so, it must be meaningful. Because it allows all the item to be reused with a Rect object thus saving resources, it is not necessarily the best, but it can effectively save resources.

One thing to note is that the OnDraw ()/ondrawover () method does not call for each item, it will only be called once to draw all of the item's decorative content. So we have to traverse all the item in this method to draw.

The previous article simply provides a divideritemdecoration source code, of course, we can inherit itemdecoration to achieve richer content.

Recyclerview.itemanimator

The Itemanimator class mainly deals with animation effects, and in the following three cases, the animation is triggered.

    • An item is added to the data set
    • An item is removed from the data set
    • A position in the interface has been moved.

Fortunately, a default implementation class is provided in the V7 Compatibility Pack called Defaultitemanimator, which, if not set, will be adapted to the class by default.

If you want the animation to take effect, it's clear that Android must know that the data has changed. In the early adapters, we needed to call the Notifydatasetchanged method to notify the Android dataset that the data set had changed. But now no longer applies, this method redraws all visible item but does not trigger any animations, we must call a method similar to the following to trigger the animation.

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

Listeners

Listeners, there are no more onitemclicklistener and Onitemlongclicklistener listeners in the Recyclerview, but we can use Onitemtouchlistener to match gestures to identify these events, This means that we need to write more code to achieve the same effect.

Sum up

Used in the layout file, the code is as follows

     <android.support.v7.widget.RecyclerView        android:id="@+id/recyclerView"        android:layout_width="match_parent"        android:layout_height="match_parent"        tools:context=".MainActivity"        tools:listitem="@layout/item_demo_01"        />

The Tools property renders the current layout, and when we switch to the visual editor, we can see the effect, and of course we can not write it, just can't see the effect.

As we can see, there are some special properties that are not used, and actually the properties of Recyclerview are derived from their parent class ViewGroup. In Recyclerview there is a way to use the AttributeSet, this method is generatelayoutparams, but inside it also does not have how to manipulate the property.

@OverridepublicgenerateLayoutParams(AttributeSet attrs) {   ifnull) {      thrownew IllegalStateException("RecyclerView has no LayoutManager");   }   return mLayout.generateLayoutParams(getContext(), attrs);}

And it's easy to use it in activity.

//Get Control ReferenceRecyclerview = (Recyclerview) Findviewbyid (R.id.recyclerview);//Instantiate layout Manager and set layout manager, scroll to topLinearlayoutmanager LayoutManager =NewLinearlayoutmanager ( This); Layoutmanager.setorientation (linearlayoutmanager.vertical); Layoutmanager.scrolltoposition (0); Recyclerview.setlayoutmanager (LayoutManager);//When the item size is the same as the optimization, specifically how to optimize the method I do not know. Recyclerview.sethasfixedsize (true);//BIND adapter and provide data setlist<demomodel> items =NewArratlist<demomodel> ();//...... The initialization of the data is done hereadapter =NewRecyclerviewdemoadapter (items); Recyclerview.setadapter (adapter);//using adorners, the source code of this class is provided in the previous articleRecyclerview.itemdecoration itemdecoration =NewDivideritemdecoration ( This, divideritemdecoration.vertical_list);//Note here is add instead of set, indicating that you can add multipleRecyclerview.additemdecoration (itemdecoration);//The following sentence can not be written, because the default is to use the class;//When we customize the animation, it is necessary to setRecyclerview.setitemanimator (NewDefaultitemanimator ());//Set listener, need mate gesture//recyclerview.addonitemtouchlistener (this);

Summarized in the following steps

    1. Get Recyclerview References
    2. Create layout Manager and add to Recyclerview
    3. Create the adapter and add it to Recyclerview
    4. Create 0 to more item adorner itemdecoration, if necessary
    5. Create a itemanimator, if necessary
    6. Create 0 to multiple listeners and add to Recyclerview

Basic source code above article, source http://download.csdn.net/detail/sbsujjbcy/8489667

This article refers to the http://www.grokkingandroid.com/first-glance-androids-recyclerview/

Use of the Android V7 Compatibility Pack Recyclerview (ii)

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.