Android Foundation - RecyclerView Drag-and-Drop Sort Side Slip Delete

Android Foundation - RecyclerView Drag-and-Drop Sort Side Slip Delete

Well, there are not too many explanations about Recycler View. You should all know it better. Hongyang Blog has a more detailed explanation: Android RecyclerView uses fully analytical experiential art-like controls . The purpose of writing this blog is that I want to realize this function in the process of learning and make a note, so I have this blog.~

item layout

We know that both Recycler View and ListView need item, eh... There's really nothing to say about this layout. After all, everyone's items are different. The following layout code is imitating Wechat. The code is as follows:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_gravity="center"
    android:background="#ffffff"
    android:gravity="center"
    android:orientation="vertical">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        android:padding="8dp">

        <ImageView
            android:id="@+id/iv_icon"
            android:layout_width="50dp"
            android:layout_height="50dp"
            android:background="@mipmap/ic_launcher" />

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="vertical">

            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:orientation="horizontal"
                android:padding="4dp">

                <TextView
                    android:id="@+id/tv_username"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_marginLeft="4dp"
                    android:layout_weight="1"
                    android:text="Li Linxiong"
                    android:textColor="#000000"
                    android:textSize="16dp" />

                <TextView
                    android:id="@+id/tv_time"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:text="22:10"
                    android:textColor="#888888"
                    android:textSize="14dp" />

            </LinearLayout>

            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:orientation="horizontal"
                android:paddingLeft="4dp">

                <TextView
                    android:id="@+id/tv_message"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_marginLeft="4dp"
                    android:text="What are you doing?"
                    android:textColor="#888888"
                    android:textSize="14dp" />
            </LinearLayout>
        </LinearLayout>
    </LinearLayout>
</LinearLayout>

Bean

With item layout, we should have corresponding beans. This is necessary. Bean code is as follows:

package com.example.lilinxiong.recycleviewdragdrop;

/**
 * Project name: RecycleViewDragDrop
 * Package name: com.example.lilinxiong.recycleviewdragdrop
 * File name: Bean
 * Creator: LLX
 * Creation time: 2017/3/28 17:22
 * Description: Bean
 */
public class Bean {
    //Name
    private String username;
    //time
    private String time;
    //Message content
    private String message;
    //Head id
    private int img_id;

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getTime() {
        return time;
    }

    public void setTime(String time) {
        this.time = time;
    }

    public String getMessage() {
        return message;
    }

    public void setMessage(String message) {
        this.message = message;
    }

    public int getImg_id() {
        return img_id;
    }

    public void setImg_id(int img_id) {
        this.img_id = img_id;
    }
}

An adapter is necessary

package com.example.lilinxiong.recycleviewdragdrop;

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.List;

/**
 * Project name: RecycleViewDragDrop
 * Package name: com.example.lilinxiong.recycleviewdragdrop
 * File name: RecycleViewAdapter
 * Creator: LLX
 * Creation time: 2017/3/28 17:29
 * Description: RecyclerView adapter
 */
public class RecycleViewAdapter extends RecyclerView.Adapter<RecycleViewAdapter.ViewHolder> {
    //List data
    private List<Bean> beanList;

    public RecycleViewAdapter(List<Bean> beanList) {
        this.beanList = beanList;
    }

    @Override
    public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.recycleview_item, parent, false);
        ViewHolder holder = new ViewHolder(view);
        return holder;
    }

    @Override
    public void onBindViewHolder(ViewHolder holder, int position) {
        Bean bean = beanList.get(position);
        holder.iv_icon.setImageResource(bean.getImg_id());
        holder.tv_username.setText(bean.getUsername());
        holder.tv_time.setText(bean.getTime());
        holder.tv_message.setText(bean.getMessage());
    }

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

    static class ViewHolder extends RecyclerView.ViewHolder {
        ImageView iv_icon;
        TextView tv_username;
        TextView tv_time;
        TextView tv_message;

        public ViewHolder(View view) {
            super(view);
            iv_icon = (ImageView) view.findViewById(R.id.iv_icon);
            tv_username = (TextView) view.findViewById(R.id.tv_username);
            tv_time = (TextView) view.findViewById(R.id.tv_time);
            tv_message = (TextView) view.findViewById(R.id.tv_message);
        }
    }
}

Implementing drag-and-drop sorting and sideslip deletion effects

Everything is available, now we can achieve our drag and drop sorting, the effect of sideslip deletion bar. Let's start with logic.

  • Binding RecyclerView controls
  • Data, adapter initialization
  • Layout Manager initialization (Linear Layout Manager initialization if you want to achieve linear drag-and-drop sorting)
  • RecyclerView Sets Layout Manager
  • RecyclerView Setup Adapter
  • ItemTouchHelper

Using a RecyclerView is essential. Binding id s, data, and adapter initialization are necessary. Layout Manager controls how data is displayed in RecyclerView. Next, layoutManager and adapter are set for RecyclerView.
The last one is the key to achieve drag-and-drop sorting and sideslip deletion. Hey hey, let's explain it in the code. If you say that, the space hole, OK, the code is as follows:

package com.example.lilinxiong.recycleviewdragdrop;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.helper.ItemTouchHelper;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class MainActivity extends AppCompatActivity {
    private RecyclerView mRecyclerView;
    private RecycleViewAdapter adapter;
    private List<Bean> beanList;
    private LinearLayoutManager layoutManager;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        //Initialization control
        initView();
        //Initialization data
        initData();

    //Initialization data
    private void initData() {
        for (int i = 0; i < 20; i++) {
            Bean bean = new Bean();
            bean.setImg_id(R.mipmap.ic_launcher);
            bean.setTime("2017-03-28");
            bean.setMessage("I learned it today. RecyclerView Drag sort, RecyclerView Side slip deletion");
            bean.setUsername("Li Linxiong");
            beanList.add(bean);
        }
        adapter.notifyDataSetChanged();
    }

    //Initialization control
    private void initView() {
        //Binding id
        mRecyclerView = (RecyclerView) findViewById(R.id.mRecyclerView);
        //beanList initialization
        beanList = new ArrayList<>();
        //adapter initialization
        adapter = new RecycleViewAdapter(beanList);
        //Layout Manager initialization
        layoutManager = new LinearLayoutManager(this);
        //RecyclerView Sets Layout Manager
        mRecyclerView.setLayoutManager(layoutManager);
        //RecyclerView Binding Adapter
        mRecyclerView.setAdapter(adapter);
    }
}

If you want to achieve drag-and-drop sorting and sideslip deletion of RecyclerView, you need the following code, as follows:

        ItemTouchHelper helper = new ItemTouchHelper(new ItemTouchHelper.Callback() {
            @Override
            public int getMovementFlags(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder) {
                //The first callback method returns int to indicate whether the direction is being monitored.
                int dragFlags = ItemTouchHelper.UP | ItemTouchHelper.DOWN;//In linear arrangement, the up and down actions are monitored: drag-and-drop sorting
                int swipeFlags = ItemTouchHelper.LEFT | ItemTouchHelper.RIGHT;//In linear arrangement, the left-right motion is monitored, while the left-right motion is: sideslip deletion.
                return makeMovementFlags(dragFlags, swipeFlags);
            }

            @Override
            public boolean onMove(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder, RecyclerView.ViewHolder target) {
                //Sliding events
                //Change of position
                Collections.swap(beanList, viewHolder.getAdapterPosition(), target.getAdapterPosition());
                //Refresh adapter
                adapter.notifyItemMoved(viewHolder.getAdapterPosition(), target.getAdapterPosition());
                return false;
            }

            @Override
            public void onSwiped(RecyclerView.ViewHolder viewHolder, int direction) {
                //Side slip events
                beanList.remove(viewHolder.getAdapterPosition());
                //Refresh adapter
                adapter.notifyItemRemoved(viewHolder.getAdapterPosition());
            }

            @Override
            public boolean isLongPressDragEnabled() {
                //Whether it can be dragged or not
                return true;
            }
        });
        helper.attachToRecyclerView(mRecyclerView);

The logic of this code is, first of all, I listen to what the action is now, that is! Fingers move up and down or left and right, up and down to exchange the location of item, left and right to remove the item data from the list, and then refresh adapter, up and down for dragging, then we should return true in isLongPress Drag Enabled, that is, allow dragging! Finally, just set up the effective Recycler View, that is! Heler. attachTo RecyclerView () This code! That's the general logic. Look at the other comments in the code. I feel quite clear. Hey hey! Look at the effect.

If we want to achieve the following effects:

Hey hey, that's the form. It's a bit ugly. Don't mind. After all, the effect is good. If we want to achieve the above effect, the change is not big. First, we need to change the format of mRecyclerView. setLayout Manager to GridLayout Manager (); then because now we don't need to right-slide or left-slide to delete it. In addition, the way we listen in ItemTouchHelper has been changed. No other changes are needed. The code is as follows:

...
        GridLayoutManager gridLayoutManager = new GridLayoutManager(MainActivity.this, 2);
        //RecyclerView Sets Layout Manager
        mRecyclerView.setLayoutManager(gridLayoutManager);
...

New GridLayout Manager (MainActivity. this, 2), which requires two parameters to be passed, the first is Context, and the second is to display several item s per line.

            @Override
            public int getMovementFlags(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder) {
                //The first callback method returns int to indicate whether the direction is being monitored.
                int dragFlags = ItemTouchHelper.UP | ItemTouchHelper.DOWN | ItemTouchHelper.LEFT | ItemTouchHelper.RIGHT;
                int swipeFlags = 0;
                return makeMovementFlags(dragFlags, swipeFlags);
            }

Since we don't need swipeFlags, just give it a value of 0, OK, so that after the modification, the effect of the above picture will be achieved! Is it very simple?

There are a lot of blogs about RecyclerView, such as the Great God of Hongyang. Creating a Universal Adapter for RecyclerView makes RecyclerView more useful Of course, there's also the opening article about Recycler View.

Well, one thing is that the code for the main layout is not written, and of course there are closures. Closures just say "compile'com.android.support:recyclerview-v7:25.2.0". The main layout is a RecyclerView. Nothing, so we don't post the code.~

If you don't know anything, you can leave a message in the comments section below. I will return it when I see it. In addition, students who are interested in android can add us. Programmer Liu Group: 555974449. There are many gods in the group. They are very enthusiastic and enthusiastic. You can ask if you don't understand them.

Demo Download

Keywords: Android Java xml encoding

Added by KresentPhresh on Sun, 14 Jul 2019 21:42:50 +0300