preface

  • RecylerViewinAndroidVery common in development
  • Today, I’m going to bring youRecylerViewI hope you will enjoy the comprehensive introduction of the web, including its definition, features, specific use, etc.

directory


Schematic diagram


1. Introduction

  • defineGoogleUsed to replaceListViewSliding component of
  • Features: more powerful functions, support more customized styles, higher scalability

2. Compare with ListView

2.1 the advantages


Schematic diagram

mRecyclerView = findView(R.id.id_recyclerview); / / set the layout manager mRecyclerView. SetLayoutManager (layout). . / / set the adapter mRecyclerView setAdapter (adapter) / / set the Item increased, remove animation mRecyclerView setItemAnimator (new DefaultItemAnimator ()); / / add divider mRecyclerView. AddItemDecoration (new DividerItemDecoration (getActivity (), DividerItemDecoration.HORIZONTAL_LIST));Copy the code
  • Q: Compared with ListView, RecyclerView basically requires the above series of steps to set up, and ListView may only need to set up a adapter can be used normally. So why add so many steps?
  • A: See RecyclerView from the name, RecyclerView recycle View, that is to say RecyclerView recycle and reuse View, the other you can go to their own Settings, you can see its high degree of decoupling, give you full customization freedom

2.2 disadvantages

RecyclerView control click, long press events is more troublesome, need to write their own


3. Application scenarios

List page display interface (need to expand, need to support animation, frequent updates & local refresh)


4. Basic concepts

4.1 RecyclerView. Adapter

Just like ListView, RecyclerView also needs an adapter, and this adapter forces us to use Viewholder to optimize performance, and getView method does not need to write itself, we just need to write Viewholder, the reuse of the View is already wrapped.

4.2 LayoutManager

Layout managers, set to LinearLayoutManager, GridLayoutManager, StaggeredGridLayoutManager can easily realize the ListView, the GridView and fluid layout list effect.

Can also manage rolling & recycling

4.3 ItemAnimator

This class can add or remove animations, and it works fine by default if you don’t want to set it.


5. Procedure

  1. Define the main XML layout
  2. Define the XML layout implemented by each row of RecyclerView as required
  3. Create an Adapter class that inherits RecyclerView.Adapter and override its methods.
  4. Define a HashMap list to store data in key-value pairs.
  5. Construct the Adapter object and set the Adapter.
  6. Bind RecyclerView to Adapter.

6. Concrete examples

  • Examples will be shown in accordance with the above steps
  • Personal recommendation first download Demo source to see the following analysis, the effect will be better: Demo source download

Step 1. Define the main XML 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" tools:context="${relativePackage}.${activityClass}" > <android.support.v7.widget.RecyclerView android:id="@+id/my_recycler_view" android:layout_width="match_parent" android:layout_height="match_parent" android:scrollbars="horizontal" /><! > </RelativeLayout>Copy the code

Using support-v7 package on AndroidStudio1.5:

  • Right-click the app directory of the file directory to go to Moudle Setting
  • Add to Dependencies
The compile 'com. Android. Support: recyclerview - v7:23.1.1'Copy the code

Step 2. Define the XML layout (item layout) list_cell.xml implemented by each row of RecyclerView as required

<? The XML version = "1.0" encoding = "utf-8"? > <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="match_parent" android:layout_height="match_parent"> <RelativeLayout android:layout_width="match_parent" android:layout_height="match_parent"> <ImageView android:layout_alignParentRight="true" android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/ItemImage"/> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="New Text" android:id="@+id/Itemtitle" /> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="New Text" android:id="@+id/Itemtext" android:layout_below="@+id/Itemtitle"/> </RelativeLayout> </LinearLayout>Copy the code

Step 3. Create an Adapter class that inherits RecyclerView.Adapter and override its methods. MyAdapter.java

package scut.receiverview; import android.content.Context; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.TextView; import java.util.ArrayList; import java.util.HashMap; /** * Created by yany on 2016/4/11. */ public class MyAdapter extends RecyclerView.Adapter { private LayoutInflater inflater; private ArrayList<HashMap<String, Object>> listItem; private MyItemClickListener myItemClickListener; public MyAdapter(Context context, ArrayList<HashMap<String, Object>> listItem) { inflater = LayoutInflater.from(context); this.listItem = listItem; Viewholder extends RecyclerView. Viewholder {private TextView Title, Text; private ImageView ima; public Viewholder(View root) { super(root); Title = (TextView) root.findViewById(R.id.Itemtitle); Text = (TextView) root.findViewById(R.id.Itemtext); ima = (ImageView) root.findViewById(R.id.ItemImage); root.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (myItemClickListener ! = null) myItemClickListener .onItemClick(v,getPosition()); }}// Call MainActivity onItemClick when clicked); } public TextView getTitle() { return Title; } public TextView getText() { return Text; } public ImageView getIma() { return ima; } } @Override public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { return new Viewholder(inflater.inflate(R.layout.list_cell, null)); } @override public void onBindViewHolder(RecyclerView.ViewHolder holder, final int position) { Viewholder vh = (Viewholder) holder; vh.Title.setText((String) listItem.get(position).get("ItemTitle")); vh.Text.setText((String) listItem.get(position).get("ItemText")); vh.ima.setImageResource((Integer) listItem.get(position).get("ItemImage")); } @override public int getItemCount() {return listitem.size (); } public void setOnItemClickListener(MyItemClickListener){MyItemClickListener = listener; }// Bind the click listener passed in by MainActivity.Copy the code

Implement click events:

  1. The click event listener is set up inside the Viewholder
  2. Call the method in MainActivity by calling the interface method of OnItemClickListener.

MyItemClickListener. Java interface: Used to implement click events

package scut.receiverview;

import android.view.View;


public interface MyItemClickListener {
    public void onItemClick(View view,int postion);
}
Copy the code

Step 4: In Mainacelasticity. Java:

  • Define a HashMap list to store data in key-value pairs.
  • Construct the Adapter object and set the Adapter
  • Bind RecyclerView to Adapter

MainActicity.java

package scut.receiverview; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.view.View; import android.widget.Toast; import java.util.ArrayList; import java.util.HashMap; public class MainActivity extends AppCompatActivity implements MyItemClickListener { private RecyclerView Rv; private ArrayList<HashMap<String,Object>> listItem; private MyAdapter myAdapter; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); initData(); initView(); } public void initData(){ listItem = new ArrayList<HashMap<String, Object>>(); /* for (int I = 0; i < 100; i++) { HashMap<String, Object> map = new HashMap<String, Object>(); Map. put("ItemTitle", "ItemTitle" + I + "); Map. put("ItemText", "this is the" + I + "line "); map.put("ItemImage",R.mipmap.ic_launcher); listItem.add(map); } } public void initView(){ Rv = (RecyclerView) findViewById(R.id.my_recycler_view); LinearLayoutManager = new LinearLayoutManager(this); Rv.setLayoutManager(layoutManager); Rv.setHasFixedSize(true); Rv.addItemDecoration(new DividerItemDecoration(this, layoutManager.getOrientation())); //Rv. AddItemDecoration (new DividerItemDecoration(this, r.dividable. List_divider)); MyAdapter = new myAdapter (this,listItem); myAdapter.setOnItemClickListener(this); Rv.setAdapter(myAdapter); } @override public void onItemClick(View View, int postion) {system.out.println (" click "+ "line "); Toast.makeText(this, (String)listItem.get(postion).get("ItemText"), Toast.LENGTH_SHORT).show(); }}Copy the code

5. The last step is to implement the line ItemDecoration

If you draw a line you can just add it, you don’t have to write this class

DividerItemDecoration.java:

package scut.receiverview; import android.content.Context; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.graphics.Rect; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.util.TypedValue; import android.view.View; Public class DividerItemDecoration extends RecyclerView. ItemDecoration {/ * * RecyclerView layout direction, RecyclerView layout can be landscape, Can also be longitudinal * horizontal and VERTICAL is not the same as the corresponding segmentation to drawing * * / private int mOrientation = LinearLayoutManager. VERTICAL; Private int mItemSize = 1; private int mItemSize = 1; /** * Private Paint mPaint; /** private Paint mPaint; /** * the constructor passes in the layout direction, Public DividerItemDecoration(context context,int orientation) {@param Context * @param orientation */ Public DividerItemDecoration(context context,int orientation) { this.mOrientation = orientation; if(orientation ! = LinearLayoutManager.VERTICAL && orientation ! = LinearLayoutManager. HORIZONTAL) {throw new IllegalArgumentException (" please to correct parameters "); } mItemSize = (int) TypedValue.applyDimension(mItemSize, TypedValue.COMPLEX_UNIT_DIP,context.getResources().getDisplayMetrics()); mPaint = new Paint(Paint.ANTI_ALIAS_FLAG) ; mPaint.setColor(Color.BLUE); /* Set the FILL */ mPaint. SetStyle (paint.style.fill); } @Override public void onDraw(Canvas c, RecyclerView parent, RecyclerView.State state) { if(mOrientation == LinearLayoutManager.VERTICAL){ drawVertical(c,parent) ; }else { drawHorizontal(c,parent) ; / / private void drawVertical(canvas,RecyclerView parent){/ / private void drawVertical(canvas,RecyclerView parent){  final int left = parent.getPaddingLeft() ; final int right = parent.getMeasuredWidth() - parent.getPaddingRight() ; final int childSize = parent.getChildCount() ; for(int i = 0 ; i < childSize ; i ++){ final View child = parent.getChildAt( i ) ; RecyclerView.LayoutParams layoutParams = (RecyclerView.LayoutParams) child.getLayoutParams(); final int top = child.getBottom() + layoutParams.bottomMargin ; final int bottom = top + mItemSize ; canvas.drawRect(left,top,right,bottom,mPaint); Private void drawHorizontal(canvas,RecyclerView) parent){ final int top = parent.getPaddingTop() ; final int bottom = parent.getMeasuredHeight() - parent.getPaddingBottom() ; final int childSize = parent.getChildCount() ; for(int i = 0 ; i < childSize ; i ++){ final View child = parent.getChildAt( i ) ; RecyclerView.LayoutParams layoutParams = (RecyclerView.LayoutParams) child.getLayoutParams(); final int left = child.getRight() + layoutParams.rightMargin ; final int right = left + mItemSize ; canvas.drawRect(left,top,right,bottom,mPaint); }} /** * Set the size of the item splitter * @param outRect * @param view * @param parent * @param state */ @override public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView. State State) {if (mOrientation = = LinearLayoutManager. VERTICAL) {outRect. Set (0, 0, mItemSize); } else {outRect. Set (mItemSize 0, 0, 0). }}}Copy the code

Effect output diagram



7. To summarize

  • This article gives a comprehensive introductionRecylerView, including its definition, characteristics, specific use, etc.
  • Next, I will continue to introduce the knowledge of Android development. If you are interested, you can follow my Jane Book blog: carsonHo’s Jane Book blog

Thumb up, please! Because your encouragement is my biggest motivation to write!

The Android event distribution mechanism is the most comprehensive and easy to understand solution for Android screen adaptation. It is the most comprehensive and easy to understand solution for Android screen adaptation. Android development: JSON introduction and the most comprehensive analysis method! BroadcastReceiver Is the most comprehensive version of Android’s BroadcastReceiver


Welcome to attentionCarson_HoJane books!

Share the dry things about Android development from time to time, the pursuit of short, flat, fast, but there is no lack of depth.