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

Auto read OTP using SMS User Consent API in Android

Some times ago Google Play restricts the use of high risk or sensitive permissions, including the SMS or Call Log permission groups. It means you have to justify why you are taking SMS or other high risk or sensitive permissions for your application .For this you may be required to complete the Permissions Declaration Form and receive approval from Google Play. Before this every app even who does not have any purpose for taking SMS or other high sensitive permissions in their app ,They was taking these permissions from users and this is a kind of security beach.  For solution of this problem Google introduce SMS User Consent API . The SMS User Consent API complements the SMS Retriever API by allowing an app to prompt the user to grant access to the content of a single SMS message. When a user gives consent, the app will then have access to the entire message body to automatically complete SMS verification. If your appeal for SMS permission is rejected by Google team you can u...

How to open pdf file url using webview in Android

 Sometimes we have requirement of showing pdf file in our Android Application. Although there are many third party gradle dependencies available online by which you can show your pdf file easily but one of the major drawback of using these libraries are they will increase you apk size .In some cases they will increase apk size upto ~14 MB. Alternatively you can access and show pdf file using assets and from storage options. This can take less size than any third party library. Here we use pdf using url and if you directly open your pdf file url in webview you will get no result because it will start downoad if you open this link in any web browser.  So in this article we will learn how we can open our pdf url using webview and without using any third party library. So lets Start step by Step:- Lets Suppose you have a pdf file url something like   http://yourwebsite.com/files/mydocumentfile.pdf Step 1: So we you this pdf file url to embed in our webview .First of all you h...