Android development-use RecyclerView to view new features of AndroidL and new features of android5.0

Source: Internet
Author: User

Android development-use RecyclerView to view new features of AndroidL and new features of android5.0

At last year's Google I/0 conference, Google opened a new view class RecyclerView, which is used to replace ListView and GridView and provides a more efficient reuse mechanism, at the same time, the decoupling of management and view is realized. Today, we will summarize this new control.

Overview

First, let's take a look at the important classes under the RecyclerView class and their functions:

  • RecyclerView. Adapter: a managed data set that creates a view for each Item;
  • RecyclerView. ViewHolder: The subview that carries the Item view;
  • RecyclerView. LayoutManager: Responsible for the layout of the Item view;
  • RecyclerView. ItemDecoration: Add a subview for each Item view, which is used to draw Divider in the Demo;
  • RecyclerView. ItemAnimator: Specifies the animation effect when data is added or deleted;
Basic usage

First, let's take a look at the basic usage of RecyclerView:

1. Create a linear layout manager LayoutManager

// Create a linear layout manager mLayoutManager = new LinearLayoutManager (this); // The default value is Vertical. mLayoutManager. setOrientation (LinearLayoutManager. VERTICAL); queue. setLayoutManager (mLayoutManager );

2. Re-upload the adapter to inherit RecyclerView. Adapter's "VH". The "Vl" indicates the ViewHolder class we usually use in ListView (this class must inherit RecyclerView. ViewHolder );

There are several important methods in the adapter that we need to add:

  • Public int getItemCount (): returns the total number of items displayed;
  • Public void onBindViewHolder;
  • Public ViewHolder onCreateViewHolder (ViewGroup view, int position): In this method, we create a ViewHolder and return it. ViewHolder must have a constructor with a View, this View is the root layout of our items. Here we can customize the layout of items;
public class MyAdapter extends RecyclerView.Adapter<MyAdapter.ViewHolder> {    private List<String> dataList;    public MyAdapter(List<String> list) {        this.dataList = list;    }    @Override    public int getItemCount() {        // TODO Auto-generated method stub        return dataList.size();    }    @Override    public void onBindViewHolder(ViewHolder viewHolder, int position) {        // TODO Auto-generated method stub        viewHolder.textView.setText(dataList.get(position));    }    @Override    public ViewHolder onCreateViewHolder(ViewGroup viewGroup, int position) {        // TODO Auto-generated method stub        View view = LayoutInflater.from(viewGroup.getContext()).inflate(                R.layout.item, null);        ViewHolder holder = new ViewHolder(view);        return holder;    }    public class ViewHolder extends RecyclerView.ViewHolder {        public TextView textView;        public ViewHolder(View view) {            super(view);            // TODO Auto-generated constructor stub            textView = (TextView) view.findViewById(R.id.item_text);        }    }}

3. Set a dataset

List<String> list = new ArrayList<String>();for (int i = 0; i < 100; i++) {    list.add("item  "+ i);}MyAdapter adapter = new MyAdapter(list);mRecyclerView.setAdapter(adapter);

Changing the LinearLayoutManager direction can be set to horizontal ListView display, which is also a powerful feature of RecyclerView, which can achieve recycling management and view decoupling.

mLayoutManager.setOrientation(LinearLayoutManager.HORIZONTAL);
How to add a split line for an Item

After simple use, we can see that the RecyclerView does not even have a basic split line. Next, let's take a look at how to add a split line for it: you can use the addItemDecoration method to add an ItemDecoration for the RecyclerView, use ItemDecoration to draw a split line for us.

There are three methods in ItemDecoration. ItemDecoration is not implemented, and we need to do it ourselves:

  • OnDraw method: it is drawn before each Item is drawn;
  • OnDrawOver: Draw after the Item is drawn;
  • GetItemOffsets you can set a certain offset for each Item through outRect. set;

Let's take a look at the Code:

Public class ItemDivider extends ItemDecoration {private Drawable mDrawable; public ItemDivider (Context context, int resId) {// here we pass in the Drawable object mDrawable = context as Divider. getResources (). getDrawable (resId) ;}@ Override public void onDrawOver (Canvas c, RecyclerView parent) {final int left = parent. getPaddingLeft (); final int right = parent. getWidth ()-parent. getPaddingRight (); final int childCount = parent. getChildCount (); for (int I = 0; I <childCount; I ++) {final View child = parent. getChildAt (I); final RecyclerView. layoutParams params = (RecyclerView. layoutParams) child. getLayoutParams (); // The following calculation is used to determine the final int top = child. getBottom () + params. bottomMargin; final int bottom = top + mDrawable. getIntrinsicHeight (); mDrawable. setBounds (left, top, right, bottom); mDrawable. draw (c) ;}@ Override public void getItemOffsets (Rect outRect, int position, RecyclerView parent) {outRect. set (0, 0, 0, mDrawable. getIntrinsicWidth ());}}

Here I wrote a shape to replace the split line:

<?xml version="1.0" encoding="utf-8"?><shape xmlns:android="http://schemas.android.com/apk/res/android"    android:shape="rectangle" >    <solid android:color="#000" />    <size android:height="2dp" /></shape>

Effect of adding a split line:

How to add click events ##

Set OnItemClickListener and OnItemLongClickListener In the Adapter.
Expose the root Layout View of the Item in ViewHolder, obtain the root Layout View in the onBindViewHolder method, set the listener, and call the listener you set.

1. First, create your own interface in MyAdapter:

public interface OnItemClickListener {    public void onClick(View parent, int position);}public interface OnItemLongClickListener {    public boolean onLongClick(View parent, int position);}

2. Publish the root Layout View in ViewHolder:

public class ViewHolder extends RecyclerView.ViewHolder {        public TextView textView;        public View itemView;        public ViewHolder(View view) {            super(view);            // TODO Auto-generated constructor stub            itemView = view;            textView = (TextView) view.findViewById(R.id.item_text);        }    }

3. Finally, set the click event for itemView in onBindViewHolder:

viewHolder.itemView.setOnClickListener(new OnClickListener() {            @Override            public void onClick(View v) {                // TODO Auto-generated method stub                if (onItemClickListener != null) {                    onItemClickListener.onClick(v, position);                }            }        });viewHolder.itemView.setOnLongClickListener(new OnLongClickListener() {            @Override            public boolean onLongClick(View v) {                // TODO Auto-generated method stub                if (onItemLongClickListener != null) {                    return onItemLongClickListener.onLongClick(v, position);                }                return false;            }        });
How to determine whether to slide to the tail or top

LinearLayoutManager provides the following methods to help developers obtain the top and bottom items on the screen:
FindFirstVisibleItemPosition ()
FindFirstCompletelyVisibleItemPosition ()
FindLastVisibleItemPosition ()
FindLastCompletelyVisibleItemPosition ()

In this way, we get the idea: Set a sliding listener event for RecyclerView and make a judgment:

MRecyclerView. setOnScrollListener (new OnScrollListener () {boolean isShowTop = false; boolean isShowBottom = false; @ Override public void onScrolled (int arg0, int arg1) {// TODO Auto-generated method stub if (mLayoutManager. findLastCompletelyVisibleItemPosition () = 99) {if (! IsShowTop) {Toast. makeText (MainActivity. this, "slide to the bottom", Toast. LENGTH_SHORT ). show () ;}isshowtop = true;} else {isShowTop = false;} if (mLayoutManager. findFirstCompletelyVisibleItemPosition () = 0) {if (! IsShowBottom) {Toast. makeText (MainActivity. this, "slide to the top", Toast. LENGTH_SHORT ). show () ;}isshowbottom = true;} else {isShowBottom = false ;}}@ Override public void onScrollStateChanged (int arg0) {// TODO Auto-generated method stub }});

Let's take a look at the effect:

Add or remove data

RecyclerView. Adapter provides two methods to adjust data addition or deletion:
Public final void policyiteminserted (int position)
Public final void policyitemremoved (int position)

In this way, you only need to provide the add or delete method in your Adapter and call the above method in the method:

    public void insert(String data, int position){        dataList.add(position, data);        notifyItemInserted(position);    }    public void remove(int position){        dataList.remove(position);        notifyItemRemoved(position);    }

Next, I click "add data" for "RecyclerView Settings" in the Activity and press "delete data;

        adapter.setOnItemClickListener(new OnItemClickListener() {            @Override            public void onClick(View parent, int position) {                // TODO Auto-generated method stub                adapter.insert("Insert", position);            }        });        adapter.setOnItemLongClickListener(new OnItemLongClickListener() {            @Override            public boolean onLongClick(View parent, int position) {                // TODO Auto-generated method stub                adapter.remove(position);                return true;            }        });

Let's take a look at the results:

ItemAnimator can be used to set the animation during loading and removal. We can use the setItemAnimator method to set the animation, but currently only DefaultItemAnimator is provided.

Source code download

Click to download source code

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.