Life isn’t easy, and if we don’t try, it just makes life more scoundrel

A few days ago, I wrote a note based on the learning of “Android Qunying Biography” about the basic use of ListView But Google has launched a more free RecyclerView to replace ListView, so these two days specially spend time to learn the basic usage of RecyclerView, today write this will realize the basic functions of RecyclerView such as basic use, add dividing line, drag and drop to move, slide delete In addition, in a few days to continue to learn more advanced functions, the overall preview:

We know that RecyclerView is used to replace ListView and GridView, so according to the last two usage,RecyclerView must have one thing, Adapter, and Adapter needs data items and view fill

  • item_viewholder.xml
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="#44ff00">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="hello"
        android:textColor="#fff"
        android:textSize="40sp"
        android:layout_gravity="center_horizontal"
        android:gravity="center"
        android:id="@+id/text_view"/>
</LinearLayout>```
* activity_main.xml
Copy the code

<android.support.v7.widget.Toolbar android:layout_width=”match_parent” android:layout_height=”? attr/actionBarSize” android:id=”@+id/tool_bar” app:title=”RecyclerDemo” app:titleTextColor=”@android:color/white” android:background=”@color/colorPrimary”> </android.support.v7.widget.Toolbar> <android.support.v7.widget.RecyclerView android:layout_width=”match_parent” android:layout_height=”match_parent” android:id=”@+id/recycler_view”> </android.support.v7.widget.RecyclerView> “`

  • The basic implementation of myAdapter.java
public class MyAadapter extends RecyclerView.Adapter{
    private LayoutInflater inflater;
    public List<String> list;
  
    public MyAadapter(Context context , List<String> list) {
        this.list = list;
        inflater = LayoutInflater.from(context);
    }

    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        return new ViewHolder(inflater.inflate(R.layout.item_viewholder,parent,false));
    }

    @Override
    public void onBindViewHolder(RecyclerView.ViewHolder holder, final int position) {
        final ViewHolder viewHolder = (ViewHolder) holder;
        viewHolder.textview.setText(list.get(position));
    }

    @Override
    public int getItemCount() {
        return list.size();
    }

    private class ViewHolder extends RecyclerView.ViewHolder{

        private TextView textview;

        public ViewHolder(View itemView) {
            super(itemView);

            textview = (TextView) itemView.findViewById(R.id.text_view);
        }
    }
}```
MainActivity.java
Copy the code

public class MainActivity extends AppCompatActivity implements Toolbar.OnMenuItemClickListener {

private RecyclerView recyclerView;
private List<String> mDatas;
private MyAadapter myAadapter;
private MyAadapter.OnClickListener mOnClickListener;
private Toolbar mToolbar;
private RecyclerView.LayoutManager manager;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    mDatas = getList();
    recyclerView = (RecyclerView) findViewById(R.id.recycler_view);
    recyclerView.setItemAnimator(new DefaultItemAnimator());
    recyclerView.setLayoutManager(new LinearLayoutManager(this));
    myAadapter = new MyAadapter(this,mDatas);
    recyclerView.setAdapter(myAadapter);
    //Toolbar
    mToolbar = (Toolbar) findViewById(R.id.tool_bar);
    setSupportActionBar(mToolbar);
    mToolbar.setOnMenuItemClickListener(this);
Copy the code

Private List getList(){List List = new ArrayList(); for (int i = ‘A’; i<‘z’; ++i){ list.add(“”+(char)i); } return list; }

One of them needs to pay attention to is' 'setLayoutManager this method sets a LayoutManager. The options are LinearLayoutManager(),GridLayoutManager(grid) and StaggerGridLayoutManager(waterfall flow) three effects! [linearLayout.gif](http://upload-images.jianshu.io/upload_images/2605454-4c18264dd6588683.gif? imageMogr2/auto-orient/strip) ! [grid.gif](http://upload-images.jianshu.io/upload_images/2605454-8ba54cceab1f52c5.gif? imageMogr2/auto-orient/strip) ! [stagger.gif](http://upload-images.jianshu.io/upload_images/2605454-125c6e07fc3f4c0f.gif? ImageMogr2 / Auto-orient /strip) just ask you, ugly is not ugly! But it doesn't matter, ugly because it has the capital to change dazzle, add a dividing line below# # # # lineTo understand the concept of line, the new is first class implements ` ` ` RecyclerView. ItemDecoration ` ` `; Then understand a few simple concepts, but a picture can solve things try to hold your tongue! [Paste_Image.png](http://upload-images.jianshu.io/upload_images/2605454-74568052f8c85b24.png? ImageMogr2 / auto - received/strip % 7 cimageview2/2 / w / 1240) from the code below a further understand * LinearLayout line categories: DividerItemDecolation. JavaCopy the code

public class DividerItemDecpration extends RecyclerView.ItemDecoration{

/ * * * system at clever use, can be customized * / private final static int [] ATTRS = {android. State Richard armitage TTR event. ListDivider}; / * * * to get the layout to * / private final static int ORIENTETION_VERTIVAL = LinearLayoutManager. VERTICAL; private final static int ORIENTATION_HORIZONTAL =LinearLayoutManager.HORIZONTAL; private Drawable mDivider; private int mOrientation; /** * Public DividerItemDecpration(Context Context,int Orientation) {TypedArray ta = context.obtainStyledAttributes(ATTRS); mDivider = ta.getDrawable(0); ta.recycle(); setOrientation(Orientation); } private void setOrientation(int Orientation){if (mOrientation! =ORIENTETION_VERTIVAL && mOrientation ! = ORIENTATION_HORIZONTAL) throw new IllegalArgumentException("Error Orientation"); mOrientation = Orientation; } / / Override public void onDraw(Canvas c, RecyclerView parent, int int, int int, int int, int int, int int, int int, int int, int int, int int, int int, int int, int int, int int, int int, int int RecyclerView.State state) { if (mOrientation == ORIENTETION_VERTIVAL){ drawVertical(c,parent); }else{ drawHorizontal(c,parent); }} /** * private void drawHorizontal(Canvas c, Canvas c) RecyclerView parent) {top final int top = parent.getpaddingTop (); Final int butTom = parent.getheight () - parent.getpaddingBottom (); final int butTom = parent.getheight () - parent.getpaddingBottom (); final int childCount = parent.getChildCount(); for (int i = 0 ; i <childCount ; ++i){ final View child = parent.getChildAt(i); final RecyclerView.LayoutParams rl = (RecyclerView.LayoutParams) child.getLayoutParams(); Final int left = child.getright () + rl.rightMargin; final int right = left + mDivider.getIntrinsicHeight(); mDivider.setBounds(left,top,right,buttom); mDivider.draw(c); }} private void drawVertical(Canvas c, RecyclerView parent) {final int left = parent.getPaddingLeft();  //parent width minus parent right final int right = parent.getwidth ()- parent.getright (); final int childCount = parent.getChildCount(); for (int i = 0 ; i <childCount ; ++i){ final View child = parent.getChildAt(i); final RecyclerView recyclerView = new RecyclerView(parent.getContext()); final RecyclerView.LayoutParams rl = (RecyclerView.LayoutParams) child.getLayoutParams(); final int top = child.getBottom() + rl.bottomMargin; final int buttom = top + mDivider.getIntrinsicHeight(); mDivider.setBounds(left,top,right,buttom); mDivider.draw(c); } } @Override public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView. State State) {if (mOrientation = = ORIENTETION_VERTIVAL) {outRect. Set (0, 0, mDivider getIntrinsicHeight ());  } else {outRect. Set (0, 0, mDivider getIntrinsicWidth (), 0). }}Copy the code

} ` ` `

  • Use method is very simple, just calladdItemDecolationMethod is effect

  • If you want more dazzling effect can be customized and other two effects, here will not demonstrate

Add click method

In addition to the separation line is a bit frustrating, there is no click method API, so we need to customize our own, we can write our method in the adapter to call MainActivity, code is as follows: myAdapter.java

public class MyAadapter extends RecyclerView.Adapter{ private LayoutInflater inflater; public List<String> list; private OnClickListener mOnItemClickListener; Public interface OnClickListener{public void OnClick(View View,int position); public boolean OnLongClick(RecyclerView.ViewHolder viewHolder,View view,int position); } public voidsetOnItemClick(OnClickListener mOnItemClickListener){
        this.mOnItemClickListener = mOnItemClickListener;

    }

    public MyAadapter(Context context , List<String> list) {
        this.list = list;
        inflater = LayoutInflater.from(context);
    }

    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        return new ViewHolder(inflater.inflate(R.layout.item_viewholder,parent,false)); } @Override public void onBindViewHolder(RecyclerView.ViewHolder holder, final int position) { final ViewHolder viewHolder = (ViewHolder) holder; viewHolder.textview.setText(list.get(position)); // Listen for the callbackif(mOnItemClickListener ! = null){ viewHolder.itemView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { int pos = viewHolder.getPosition(); mOnItemClickListener.OnClick(viewHolder.itemView,pos); }}); viewHolder.itemView.setOnLongClickListener(new View.OnLongClickListener() {
                @Override
                public boolean onLongClick(View v) {
                    int pos = viewHolder.getPosition();
                    mOnItemClickListener.OnLongClick(viewHolder,viewHolder.itemView,pos);
                    return false; }}); } } @Override public intgetItemCount() {
        returnlist.size(); } private class ViewHolder extends RecyclerView.ViewHolder{ private TextView textview; public ViewHolder(View itemView) { super(itemView); textview = (TextView) itemView.findViewById(R.id.text_view); }}} ' 'mainActivity. Java simply calls the method from Adapter in MainActivityCopy the code

myAadapter.setOnItemClick(new MyAadapter.OnClickListener() { @Override public void OnClick(View view, int position) { Toast.makeText(MainActivity.this,(position+1)+”onclick”,Toast.LENGTH_SHORT).show(); }

@Override public boolean OnLongClick(RecyclerView.ViewHolder viewHolder, View view, int position) { Toast.makeText(MainActivity.this,(position + 1)+"onLongClick",Toast.LENGTH_SHORT).show(); if (position ! = mDatas.size()-1){ helper.startDrag(viewHolder); } return false; }}); ` ` `Copy the code

The effect

The basic development

If RecyclerView were just like this I choose dog belts, but it certainly isn’t, otherwise Google wouldn’t be able to implement RecyclerView with 2W lines of code. Let’s start showing off some of his great little features

  1. Dynamic add remove in the ListView we used to add an Item or remove an Item, a little difficult, but RecyclerView allows you to step to the site, check the document you can find RecyclerView.Adapter uses two methodsnotifyItemInserted(position);.notifyItemRemoved(position);We can simply wrap it in our Adapter Adapter and customize two Menu items using the Toolbar. Click Add and remove menu. XML
<menu xmlns:android="http://schemas.android.com/apk/res/android"      xmlns:app="http://schemas.android.com/apk/res-auto">
    <item
        android:title="@string/add"
        android:id="@+id/id_btn_add"
        app:showAsAction="ifRoom"
        android:orderInCategory="80" />
    <item
        android:title="@string/remove"
        android:id="@+id/id_btn_remove"
        app:showAsAction="ifRoom"
        android:orderInCategory="90" />
</menu>```
MyAdapter.java
Copy the code

public void insertOne(int position){ list.add(“Insert One”); notifyItemInserted(position); }

public void removeOne(int position){ list.add("remove One"); notifyItemRemoved(position); } ` ` `Copy the code

The effect

2. Drag and slide to delete The helper class ItemTouchHelper requires a CallBack, so we’ll write a class extension from ItemTouchHelper.callback MyCallBack.java

public class MyCallBack extends ItemTouchHelper.Callback{ private List<String> mDatas; private MyAadapter adapter; public MyCallBack(MyAadapter adapter) { this.adapter = adapter; this.mDatas = adapter.list; / / Override public int getMovementFlags(RecyclerView, RecyclerView); RecyclerView.ViewHolder viewHolder) { final int dragFlags ,swipFlags; /** * The grid direction is UP,Down,left,right */if (recyclerView.getLayoutManager() instanceof GridLayoutManager){
            dragFlags= ItemTouchHelper.UP|
                    ItemTouchHelper.DOWN|ItemTouchHelper.LEFT|ItemTouchHelper.RIGHT;
            swipFlags = 0;
        }else{/ / LineaLayout only Up and Down dragFlags = ItemTouchHelper. Up | ItemTouchHelper. Down; // Swipe right to delete swipFlags = ItemTouchHelper.end; }returnmakeMovementFlags(dragFlags,swipFlags); } @Override public boolean onMove(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder, RecyclerView.ViewHolder target) { int framPosition = viewHolder.getAdapterPosition(); int toPosition = target.getAdapterPosition(); /** * drag */ upif (framPosition > toPosition){
            for(int i = framPosition ; i < toPosition; ++i){ Collections.swap(mDatas,i,i+1); } /** * drag down */}else {
            for(int i = framPosition ; i > toPosition ; ++i){ Collections.swap(mDatas,i,i-1); } } adapter.notifyItemMoved(framPosition,toPosition);return true; / / Override public void onSwiped(recyclerViewholder.ViewHolder); / / Override public void onSwiped(recyclerViewholder viewHolder, int direction) { int position = viewHolder.getAdapterPosition(); adapter.notifyItemRemoved(position); adapter.list.remove(position); } /** * whether to drag */ @override public BooleanisLongPressDragEnabled() {
        return false; }} ' 'then use ItemTouchHelper's startDrag(viewHolder) for the long-press event we previously customized in the MainActivity, as follows: /** * drag event */ final ItemTouchHelper helper = new ItemTouchHelper(new MyCallBack(myAadapter)); helper.attachToRecyclerView(recyclerView); myAadapter.setOnItemClick(new MyAadapter.OnClickListener() {
            @Override
            public void OnClick(View view, int position) {
                Toast.makeText(MainActivity.this,(position+1)+"onclick",Toast.LENGTH_SHORT).show();
            }

            @Override
            public boolean OnLongClick(RecyclerView.ViewHolder viewHolder,
                                       View view, int position) {
                Toast.makeText(MainActivity.this,(position + 1)+"onLongClick",Toast.LENGTH_SHORT).show();
                if(position ! = mDatas.size()-1){ helper.startDrag(viewHolder); }return false; }}); ` ` ` effect! [drag.gif](http://upload-images.jianshu.io/upload_images/2605454-60ab91d0610e7db9.gif? ImageMogr2 / Auto-Orient/Strip) If such a simple implementation of such a cool feature is not in love with it, it does not matter that the following learning will be more cool##### If you think this article is wrong, please point out, mutual communication and common progress.
Copy the code