Use of the android v7 compatibility package RecyclerView (2), recyclerview

Source: Internet
Author: User

Use of the android v7 compatibility package RecyclerView (2), recyclerview

Previous Article Use of the android v7 compatibility package RecyclerView (1)I talked about the most basic usage of RecyclerView, and now I am going to explore more details.
In the RecyclerView API, there is such a sentence

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

Generally, when a large amount of data is displayed in a limited window, RecyclerView is a flexible View to solve this problem.

The preceding description shows the application scenarios of RecyclerView. If we have a large amount of data of the same type to be displayed on the screen, and at this time it is very likely that the entire screen will not be able to fully display all the data, RecyclerView is a suitable choice. When you scroll up or down the screen, the reuse of items is also carried out at the same time. When a new item enters the visible range, there must be an old item out of the visible range, the removed item is recycled. So what is the function of recycling items cyclically? In fact, it is a very useful method because it saves CPU resources and memory.

Maybe you will say that we have been using ListView for a long time. What is the difference between RecyclerView and our previous method? In the past, when we used listview, we showed that, loop reuse and other things are coupled to a certain extent. Now RecyclerView provides a more flexible way.

The method that Google uses now does not care about what RecyclerView sees, or whether the elements are correctly displayed, or how each element is separated. RecyclerView only does recycling. Therefore, the name is RecyclerView.

The following are the most important classes related to RecyclerView.

Adapter: Adapter, bind a dataset
ViewHolder: Save the view based on the current data
LayoutManager: layout manager. How to place items
ItemDecoration: barely understood as the item decorator, which can beautify the item
ItemAnimator: animation. When an item is added, deleted, or placed again, it has an animation effect.

ViewHolder

Android has recommended the ViewHolder mode for a long time, because it can greatly improve the efficiency and increase the smoothness of the interface. The RecyclerView adapter is an internal class. We extend our subclass by inheriting it, just like this.

Public final static class ListItemViewHolder extends RecyclerView. viewHolder {TextView title; // TextView description, an element on the item interface; // an element on the item interface // Of course, public ListItemViewHolder (View itemView) can be added) {super (itemView); // reference title = (TextView) itemView. findViewById (R. id. title); description = (TextView) itemView. findViewById (R. id. description );}}
RecyclerView. Adapter

The adapter provides two main functions: it establishes the relationship between the Basic Dataset and the layout of a single item. Adapter is an important part of Android. It is used in many places, such as ListView, AutoCompleteTextView, and Spinner all use the adapter.

Google uses the internal class Adapter of RecyclerView instead of the traditional Adapter, so in RecyclerView, you will not see an Adapter like SimpleCursorAdapter and ArrayAdapter.

Unfortunately, Google does not provide the default implementation class of RecyclerView. Adapter. It is an abstract class, so we must implement three methods.

Public h_oncreateviewholder (ViewGroup parent, int viewType)
Public void onBindViewHolder (h_holder, int position)
Public int getItemCount ()

* H _ is a generic type inherited from ViewHolder. The specific type must be provided in the subclass. The basic adapter syntax is as follows:

public class RecyclerViewAdapter extends         RecyclerView.Adapter        <RecyclerViewAdapter.ItemViewHolder> {    private List<DemoModel> items;    RecyclerViewAdapter(List<DemoModel> modelData) {        if (modelData == null) {            throw new IllegalArgumentException(                  "modelData must not be null");        }        this.items = modelData;    }    @Override    public ItemViewHolder onCreateViewHolder(            ViewGroup viewGroup, int viewType) {        View itemView = LayoutInflater.                from(viewGroup.getContext()).                inflate(R.layout.item,viewGroup,false);        return new ItemViewHolder(itemView);    }    @Override    public void onBindViewHolder(            ItemViewHolder viewHolder, int position) {        DemoModel model = items.get(position);        viewHolder.title.setText(model.getTitle());        viewHolder.description.setText(model.getDescription());    }    @Override    public int getItemCount() {        return items.size();    }    public final static class ItemViewHolder            extends RecyclerView.ViewHolder {        // ... shown above in the ViewHolder section    }}
RecyclerView. LayoutManager

The layout manager is the most interesting part of RecyclerView. It is responsible for layout all sub-items. In the latest v7 compatible library, it has three implementation classes, they are LinearLayoutManager (linear layout), GridLayoutManager (a grid layout), and StaggeredGridLayoutManager (Stream layout). By default, if we do not set the layout manager, linear layout is used. We can inherit this class to implement our own layout manager, and we decide how to place the item content. However, when you look at the code of the above three implementation classes, you will find that this is not easy... Code is long... Really! The specific use of the layout manager will open another blog. Here we will introduce the simple use of the linear layout manager. The Code is as follows:

// Instantiate the object LinearLayoutManager layoutManager = new LinearLayoutManager (context); // set the layout direction to vertical layoutManager. setOrientation (LinearLayoutManager. VERTICAL); // scroll to the layoutManager. scrollToPosition (currPos); // sets the layout manager recyclerView. setLayoutManager (layoutManager );
RecyclerView. ItemDecoration

Let me call it an item decorator. Using ItemDecoration, we can increase the offset, split line, highlight, and so on for the item. We can add multiple ItemDecoration items. RecyclerView will traverse all ItemDecoration items in sequence 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 blocked by the item content, but the content you draw in onDrawOver will be drawn above the item. We can use offset to separate items. However, if you want to display a split line, you have to use the onDrawOver method to draw a separation line explicitly.

The layout manager will call the getItemOffset method in the measurement phase. It looks a little strange with a Rect-type parameter outRect, so why not use a return value to replace it? Since Google has done so, it must be meaningful. This saves resources because it allows all items to reuse a Rect object. This is not necessarily the best, but it can effectively save resources.

It is worth noting that the onDraw ()/onDrawOver () method is not called for each item. It is called only once to draw the decoration content of all items. Therefore, we must traverse all items in this method to draw.

The previous article briefly provided a DividerItemDecoration source code. Of course, we can inherit ItemDecoration to implement richer content.

RecyclerView. ItemAnimator

The ItemAnimator class mainly deals with animation effects. In the following three cases, the animation is triggered.

  • An item is added to the dataset.
  • An item is removed from the dataset.
  • One item is moved in the interface

Fortunately, a default implementation class named DefaultItemAnimator is provided in the v7 compatibility package. If it is not set, the default class will be used.

To make the animation take effect, it is obvious that android must know that the data has changed. In earlier adapters, we needed to call the yydatasetchanged method to notify the android dataset to change. But it is no longer applicable now. This method will repaint all visible items but will not trigger any animation. We must call a method similar to the following to trigger the animation.

Public final void policyiteminserted (int position)
Public final void policyitemremoved (int position)

Listeners

Listeners and RecyclerView do not have OnItemClickListener and OnItemLongClickListener listeners. However, we can use OnItemTouchListener and use gestures to identify these events, which means we need to write more code to achieve the same effect.

To sum up

Use the following code in the layout file:

     <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 attribute renders the current layout. When we switch to the visual editor, we can see the effect. Of course, we can also leave it empty, but we can't see the effect.

We can see that some special attributes are not used. In fact, the attributes of RecyclerView are all from its parent class ViewGroup. In the RecyclerView, AttributeSet is used for a method called generateLayoutParams, but it does not perform any operations on attributes internally.

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

It is also very easy to use in Activity.

// Obtain the Control Reference recyclerView = (RecyclerView) findViewById (R. id. recyclerView); // instantiate the layout manager and set the layout manager to scroll to the top of the LinearLayoutManager layoutManager = new LinearLayoutManager (this); layoutManager. setOrientation (LinearLayoutManager. VERTICAL); layoutManager. scrollToPosition (0); recyclerView. setLayoutManager (layoutManager); // optimization is helpful when the item size is the same. I do not know how to optimize it .. RecyclerView. setHasFixedSize (true); // bind the adapter and provide the dataset List <DemoModel> items = new ArratList <DemoModel> ();//...... here, the data initialization work adapter = new RecyclerViewDemoAdapter (items); recyclerView. setAdapter (adapter); // use the decorator. The source code of this class provides RecyclerView in the previous article. itemDecoration itemDecoration = new DividerItemDecoration (this, DividerItemDecoration. VERTICAL_LIST); // you can add multiple recyclerviews instead of set. addItemDecoration (itemDecoration); // The following sentence can be left blank, because this class is used by default; // when we customize an animation, it is necessary to set recyclerView. setItemAnimator (new DefaultItemAnimator (); // sets the listener, which must be associated with a gesture // recyclerView. addOnItemTouchListener (this );

Summary:

Basic source code with the previous article, source code http://download.csdn.net/detail/sbsujjbcy/8489667

This article referencesHttp://www.grokkingandroid.com/first-glance-androids-recyclerview/

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.