Skip to main content

How to implement drag and drop feature in android with click reference in Android

 Hi guys ,hope you are doing well. In this tutorial we will learn how to implement drag and drop feature in our android apllication with respect to onclick of particular view. You may utilize the Android drag/drop framework to enable your users to move data with a graphical drag and drop action. 

Sample Use Cases for Drag & Drop

- Something that helps you drag a pointer on live data to get the color of the object or the thing

- In your mobile device’s launcher screen, where every program displays, we may effortlessly drag and drop app icons from one location to another.

so without taking much time let's move to the coding part and understand step by step process.

Step 1: Create activity_drag_and_drop.xml into layout folder

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    >


    <LinearLayout
        android:id="@+id/linear_layout1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical">

        <Button
            android:id="@+id/button1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Button 1"
            android:padding="10dp"
            android:layout_margin="10dp"
            android:longClickable="true"
            android:tag="button"/>

        <Button
            android:id="@+id/button2"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Button 2"
            android:padding="10dp"
            android:layout_margin="10dp"
            android:longClickable="true"
            android:tag="button"/>
        <Button
            android:id="@+id/button3"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Button 3"
            android:padding="10dp"
            android:layout_margin="10dp"
            android:longClickable="true"
            android:tag="button"/>
        <Button
            android:id="@+id/button4"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Button 4"
            android:padding="10dp"
            android:layout_margin="10dp"
            android:longClickable="true"
            android:tag="button"/>

        <Button
            android:id="@+id/button5"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Button 5"
            android:padding="10dp"
            android:layout_margin="10dp"
            android:longClickable="true"
            android:tag="button"/>

    </LinearLayout>


    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Drop Here"
        android:textSize="12sp"
        android:textColor="#000"
        android:layout_marginLeft="20dp"
        android:layout_marginRight="20dp"
        android:layout_marginTop="30dp">

    </TextView>

    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Delete List"
        android:layout_marginRight="15dp"
        android:textColor="#FD0000"
        android:layout_gravity="right"
        android:gravity="right"
        android:id="@+id/deletelist"></TextView>


    <LinearLayout
        android:id="@+id/favorite_list"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="@drawable/drop_area_background"
        android:orientation="horizontal"
        android:layout_marginTop="20dp">

        <!-- Add other views or buttons here -->

    </LinearLayout>

</LinearLayout>

Step 2: Create DragandDrop.java file 

package com.MyApplication;

import androidx.appcompat.app.AppCompatActivity;

import android.content.ClipData;
import android.content.ClipDescription;
import android.os.Bundle;
import android.view.DragEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

public class DragandDrop extends AppCompatActivity implements View.OnClickListener {
    private LinearLayout favoriteList;
    TextView deletelist;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_drag_and_drop);

        favoriteList = findViewById(R.id.favorite_list);

        Button button1 = findViewById(R.id.button1);
        Button button2 = findViewById(R.id.button2);
        Button button3 = findViewById(R.id.button3);
        Button button4 = findViewById(R.id.button4);
        Button button5 = findViewById(R.id.button5);

        deletelist=(TextView)findViewById(R.id.deletelist);




        button1.setOnClickListener(this);


        button2.setOnClickListener(this);


        button1.setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View v) {
                ClipData clipData = ClipData.newPlainText("Button 1", "Button 1");
                View.DragShadowBuilder shadowBuilder = new View.DragShadowBuilder(v);
                v.startDragAndDrop(clipData, shadowBuilder, v, 0);
                return true;
            }
        });

        button2.setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View v) {
                ClipData clipData = ClipData.newPlainText("Button 2", "Button 2");
                View.DragShadowBuilder shadowBuilder = new View.DragShadowBuilder(v);
                v.startDragAndDrop(clipData, shadowBuilder, v, 0);
                return true;
            }
        });
        button3.setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View v) {
                ClipData clipData = ClipData.newPlainText("Button 3", "Button 3");
                View.DragShadowBuilder shadowBuilder = new View.DragShadowBuilder(v);
                v.startDragAndDrop(clipData, shadowBuilder, v, 0);
                return true;
            }
        });
        button4.setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View v) {
                ClipData clipData = ClipData.newPlainText("Button 4", "Button 4");
                View.DragShadowBuilder shadowBuilder = new View.DragShadowBuilder(v);
                v.startDragAndDrop(clipData, shadowBuilder, v, 0);
                return true;
            }
        });
        button5.setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View v) {
                ClipData clipData = ClipData.newPlainText("Button 5", "Button 5");
                View.DragShadowBuilder shadowBuilder = new View.DragShadowBuilder(v);
                v.startDragAndDrop(clipData, shadowBuilder, v, 0);
                return true;
            }
        });



        favoriteList.setOnDragListener(new View.OnDragListener() {
            @Override
            public boolean onDrag(View v, DragEvent event) {
                int action = event.getAction();
                switch (action) {
                    case DragEvent.ACTION_DRAG_STARTED:
                        // Check if the dragged view is a button
                        if (event.getClipDescription().hasMimeType(ClipDescription.MIMETYPE_TEXT_PLAIN)) {
                            return true;
                        }
                        return false;
                    case DragEvent.ACTION_DROP:
                        // Get the dragged view and its parent


                        if(favoriteList.getChildCount()>4)
                        {
                            Toast.makeText(DragandDrop.this, "You can Add Only 4 Items to Favorite List!!", Toast.LENGTH_SHORT).show();
                        }
                        else {


                            View draggedView = (View) event.getLocalState();
                            ViewGroup draggedViewParent = (ViewGroup) draggedView.getParent();
                            // Remove the dragged view from its current parent
                            //     draggedViewParent.removeView(draggedView);
                            // Add the dragged view to the linear layout


                            boolean isAlreadyPresent = false;
                            for (int i = 0; i < favoriteList.getChildCount(); i++) {
                                View childView = favoriteList.getChildAt(i);
                                if (childView.getId() == draggedView.getId()) {
                                    isAlreadyPresent = true;
                                    break;
                                }
                            }

                            // If the dragged view is not already present, add it to the favoriteList
                            if (!isAlreadyPresent) {
                                final Button droppedButton = new Button(DragandDrop.this);
                                droppedButton.setText(((Button) draggedView).getText());
                                droppedButton.setLayoutParams(new LinearLayout.LayoutParams(
                                        LinearLayout.LayoutParams.WRAP_CONTENT,
                                        LinearLayout.LayoutParams.WRAP_CONTENT
                                ));
                                droppedButton.setId(((Button) draggedView).getId());
                                droppedButton.setOnClickListener(DragandDrop.this);

                                favoriteList.addView(droppedButton);
                            } else {
                                Toast.makeText(DragandDrop.this, "Item Already Present!!", Toast.LENGTH_SHORT).show();
                            }


                        }



                     //   favoriteList.addView(draggedView);
                        return true;
                    case DragEvent.ACTION_DRAG_ENDED:
                        // Set the visibility of the dragged view to VISIBLE

                        if(favoriteList.getChildCount()>4)
                        {
                            Toast.makeText(DragandDrop.this, "You can Add Only 4 Items to Favorite List!!", Toast.LENGTH_SHORT).show();
                        }
                        else {


                            View endedView = (View) event.getLocalState();
                            endedView.setVisibility(View.VISIBLE);





                        }

                        return true;
                }
                return false;
            }
        });



        deletelist.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                favoriteList.removeAllViews();
                    Toast.makeText(DragandDrop.this, "List is Cleared!!", Toast.LENGTH_SHORT).show();

            }
        });


    }

    @Override
    public void onClick(View v) {


        switch (v.getId())
        {
            case R.id.button1:
                Toast.makeText(DragandDrop.this, "Button 1 Clicked", Toast.LENGTH_SHORT).show();
                break;

            case R.id.button2:
                Toast.makeText(DragandDrop.this, "Button 2 Clicked", Toast.LENGTH_SHORT).show();
                break;
        }
    }
}

Step 3: Don't forget to register this activity on app's manifest.xml file

 <activity
            android:name=".DragandDrop"
            android:exported="true"
            android:screenOrientation="portrait" />

That's all! Now it's time to compile and run this program and get the result.


Thank you for your time. If you like this article please share this to your network.

Comments

Popular posts from this blog

How to Download Apk file from Url and Install Programmatically

In this post we learn about download apk file from server or website and then install it Programmatically in Phone. Sometimes we have to download external apk file from server and then install if downloading successfully finished.For this we use AsyncTask class  for background process. So here is Code Snippet for this task.Lets Start :- Before this we have to add these Permissions in Manifest.xml file : <uses-permission android:name="android.permission.INTERNET" /> <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /> <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" /> DownloadNewVersion.java class DownloadNewVersion extends AsyncTask<String,Integer,Boolean> { @Override protected void onPreExecute() { super.onPreExecute(); bar = new ProgressDialog(getActivity()); bar.setCancelable(false); bar.setMessage("Downl...

How to Implement Item Click Interface in Android?

In Android development, creating interactive lists is essential to most apps. Often, these lists include items that users can click on to trigger actions such as opening a new screen or displaying more information. In this tutorial, we’ll walk through how to implement an item click interface in Android using Java and XML. By the end of this guide, you’ll know how to create a RecyclerView with an item click listener that responds to user taps. This approach is widely used in modern Android development because RecyclerView is both flexible and efficient. Step 1: Set Up Your Android Project First, create a new Android project in Android Studio. Make sure to choose Java as the programming language. Step 2: Add Dependencies Make sure that you have the required dependencies for RecyclerView in your build.gradle file. If not, add them like this: dependencies {     implementation 'androidx.recyclerview:recyclerview:1.2.1' } Sync the project after adding the dependency. Step 3: Define ...

Working with Android 11 (Changes and Security Features)

 Hello everyone , I am here with new article which is hot topic nowadays "Android 11" .The stable version of Android.  Android 11 is the eleventh major release and 18th version of Android, the mobile operating system developed by the Open Handset Alliance led by Google. It was released on September 8, 2020.It is comes with many security features and other features as well . And it is now compulsory in play store  to upload new apps with API lavel 30 which is compatible with Android 11 and from November onwards old apps also have to update with API 30 .Some other guidelines you can check out from here . Play Store Guidelines So its clear that we have to update our apps with API level 30 .But Android 11 comes with some changes as well which we have to do in our projects. For example from Android developer site "Android 11 (API level 30) further enhances the platform, giving better protection to app and user data on external storage. ". Scoped storage enforcement: Apps...