Saturday, December 28, 2024
Google search engine
HomeLanguagesJavaHow to Add Drag And Drop Feature in Android RecyclerView?

How to Add Drag And Drop Feature in Android RecyclerView?

Drag And Drop feature is very helpful. It is very simple and easy to implement. It is used in many apps that are famous, and if we’re doing some project it is very convenient to implement it. You should know the RecyclerAdapter Class. A sample video is given below to get an idea about what we are going to do in this article.

Step-by-Step Implementation

Step 1: Create a New Project in Android Studio

To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Java as the programming language.

Step 2:

Create One Recycler View in activity_main.xml and give an id of your recycler view as your choice. We are using RecyclerView Id as recyclerView.

XML




<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">
      
      <androidx.recyclerview.widget.RecyclerView
        android:id="@+id/recyclerView"
        android:layout_width="0dp"
        android:layout_height="0dp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layoutManager="androidx.recyclerview.widget.LinearLayoutManager"/>
    
</androidx.constraintlayout.widget.ConstraintLayout>


Step 3:

Create one xml file res > layout > name of the activity you want. We are using the name row_item.xml for displaying the list that we created with the image and we can use that in RecycleAdapter Class.

XML




<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout 
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="@android:color/white"
    android:foreground="?attr/selectableItemBackground">
      
      <ImageView
        android:id="@+id/imageView"
        android:layout_width="48dp"
        android:layout_height="48dp"
        android:layout_marginStart="16dp"
        android:layout_marginTop="16dp"
        android:layout_marginBottom="16dp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:srcCompat="@mipmap/ic_launcher" />
    
    <TextView
        android:id="@+id/textView"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginStart="16dp"
        android:layout_marginEnd="8dp"
        android:text="TextView"
        android:textAppearance="@style/TextAppearance.AppCompat.Large"
        app:layout_constraintBottom_toTopOf="@+id/rowCountTextView"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toEndOf="@+id/imageView"
        app:layout_constraintTop_toTopOf="parent" />
    
    <TextView
        android:id="@+id/rowCountTextView"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginEnd="8dp"
        android:text="TextView"
        android:textAppearance="@style/TextAppearance.AppCompat.Small"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="@+id/textView"
        app:layout_constraintTop_toBottomOf="@+id/textView" />
  
</androidx.constraintlayout.widget.ConstraintLayout>


Step 4:

It is the RecyclerAdapter.java class that is used to implement the RecyclerView. To add the implementation Of the View Holder Right click after adding RecyclerView.Adapter<RecyclerAdapter.ViewHolder> And implement all three methods.

 

Java




package com.android.gfgapp;
  
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
  
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
  
import java.util.List;
  
public class RecyclerAdapter extends RecyclerView.Adapter<RecyclerAdapter.ViewHolder> {
        
    private static final String TAG = "RecyclerAdapter";
    List<String> citiesList;
        
      // create constructor by right clicking
    public RecyclerAdapter(List<String> citiesList) {
        this.citiesList = citiesList;
    }
  
    @NonNull
    @Override
    public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        LayoutInflater layoutInflater = LayoutInflater.from(parent.getContext());
        
        // Make Sure the Activity You Created in Step3 you 
        // use that only inplace of row_item
        View view = layoutInflater.inflate(R.layout.row_item, parent, false);
        ViewHolder viewHolder = new ViewHolder(view);
        return viewHolder;
    }
  
    @Override
    public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
        holder.rowCountTextView.setText(String.valueOf(position));
        holder.textView.setText(citiesList.get(position));
    }
  
    @Override
    public int getItemCount() {
        return citiesList.size();
    }
  
    class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
  
        ImageView imageView;
        TextView textView, rowCountTextView;
  
        public ViewHolder(@NonNull View itemView) {
            super(itemView);
            imageView = itemView.findViewById(R.id.imageView);
            textView = itemView.findViewById(R.id.textView);
            rowCountTextView = itemView.findViewById(R.id.rowCountTextView);
            itemView.setOnClickListener(this);
        }
        
        @Override
        public void onClick(View view) {
            Toast.makeText(view.getContext(), citiesList.get(getAdapterPosition()), Toast.LENGTH_SHORT).show();
        }
        
    }
}


Step 5:

In this step A Basic Main Activity That Implements the Recycler view and A list of various cities around the world and then implemented the RecyclerView and we also have RecyclerAapterClass which is used to implement Recycler view we don’t have to do anything in the RecyclerAdapter class And then we have to create a simple Callable that was created using ItemTouchHelper class

 

MainActivity.java

Java




package com.android.gfgapp;
  
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.DividerItemDecoration;
import androidx.recyclerview.widget.ItemTouchHelper;
import androidx.recyclerview.widget.RecyclerView;
import android.os.Bundle;
  
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
  
public class MainActivity extends AppCompatActivity {
  
    RecyclerView recyclerView;
    RecyclerAdapter recyclerAdapter;
  
    List<String> citiesList;
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        citiesList = new ArrayList<>();
  
        citiesList.add("Tokyo");
        citiesList.add("New York City");
        citiesList.add("Paris");
        citiesList.add("London");
        citiesList.add("Dubai");
        citiesList.add("Singapore");
        citiesList.add("Hong Kong");
        citiesList.add("Shanghai");
        citiesList.add("Los Angeles");
        citiesList.add("Chicago");
        citiesList.add("Miami");
        citiesList.add("Sydney");
        citiesList.add("Rio de Janeiro");
        citiesList.add("Cape Town");
        citiesList.add("Mumbai");
        citiesList.add("Bangkok");
        citiesList.add("Moscow");
        citiesList.add("Rome");
        citiesList.add("Barcelona");
        citiesList.add("Toronto");
        citiesList.add("Berlin");
        citiesList.add("Istanbul");
        citiesList.add("Tokyo");
        citiesList.add("Vancouver");
  
        recyclerView = findViewById(R.id.recyclerView);
        recyclerAdapter = new RecyclerAdapter(citiesList);
        recyclerView.setAdapter(recyclerAdapter);
  
        DividerItemDecoration dividerItemDecoration = new DividerItemDecoration(this, DividerItemDecoration.VERTICAL);
        recyclerView.addItemDecoration(dividerItemDecoration);
  
        ItemTouchHelper itemTouchHelper = new ItemTouchHelper(simpleCallback);
        itemTouchHelper.attachToRecyclerView(recyclerView);
    }
  
    ItemTouchHelper.SimpleCallback simpleCallback = new ItemTouchHelper.SimpleCallback(ItemTouchHelper.UP | ItemTouchHelper.DOWN | ItemTouchHelper.START | ItemTouchHelper.END, 0) {
          
          @Override
        public boolean onMove(@NonNull RecyclerView recyclerView, @NonNull RecyclerView.ViewHolder viewHolder, @NonNull RecyclerView.ViewHolder target) {
  
            int fromPosition = viewHolder.getAdapterPosition();
            int toPosition = target.getAdapterPosition();
            Collections.swap(citiesList, fromPosition, toPosition);
            recyclerView.getAdapter().notifyItemMoved(fromPosition, toPosition);
            return false;
        }
        
        @Override
        public void onSwiped(@NonNull RecyclerView.ViewHolder viewHolder, int direction) {
  
        }
    };
  
}


Output:

RELATED ARTICLES

Most Popular

Recent Comments