Drag Drop Application Using Android Studio

Somewhere we played a game of dragging objects to an appropriate location. We will develop something like this with the same functionality. I have created a mockup of our application.

DragAndroid1.jpg

So let's start with our new application. You know very well how to create a new project and which type of parameter you need to pass. If not then visit http://www.c-sharpcorner.com/UploadFile/88b6e5/first-application-in-android-studio/ .

Note: This project requires a minimum SDK version of 12 or greater.

Step 1:

Open your "values/strings.xml" file. We need to create some string resources inside it.

Strings.xml

<string name="intro">Place following persons in Appropriate Position.</string>

 

    <string name="option_1">Mahesh Chand</string>

    <string name="option_2">Praveen Kumar</string>

 

    <string name="choice_1">Founder and Editor-in-Chief</string>

    <string name="choice_2">Editorial Director, Product Manager</string>

Step 2:

To provide a background color effect, we need to create a custom shape and will pass this to option views. So use the following procedure.

Click on "Project" then open the "res" directory then right-click and select "New" -> "Android Resource File".

Then enter name "option.xml" and select "drawable" from the drop down list.

Option.xml
 

<shape xmlns:android="http://schemas.android.com/apk/res/android"

    android:dither="true" >

    <solid android:color="#ffffaa77" />

    <corners android:radius="2dp" />

    <stroke

        android:width="2dp"

        android:color="#ffffaa77" />

    <padding

        android:bottom="5dp"

        android:left="10dp"

        android:right="10dp"

        android:top="5dp" />

</shape>


Step 3:

To provide a background color effect, we need to create a custom shape and pass it to choice views. So use the following procedure.

Click on "Project" then open the "res" directory then right-click and select "New" -> "Android Resource File".

Then enter the name "choice.xml" and select "drawable" from the drop down list.

choice.xml
 

<shape xmlns:android="http://schemas.android.com/apk/res/android"

    android:dither="true" >

    <solid android:color="#ffffff99" />

    <corners android:radius="2dp" />

    <stroke

        android:dashGap="4dp"

        android:dashWidth="2dp"

        android:width="2dp"

        android:color="#ffffff00" />

    <padding

        android:bottom="5dp"

        android:left="5dp"

        android:right="5dp"

        android:top="5dp" />

</shape>

Step 4:


Now, open your layout file and paste in the following code.

Activity_drag_drop.xml
 

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"

              android:layout_width="fill_parent"

              android:layout_height="wrap_content"

              android:orientation="vertical"

              android:padding="10dp"

              android:paddingLeft="50dp"

              android:paddingRight="50dp" >

 

    <TextView

            android:id="@+id/option_1"

            android:layout_width="fill_parent"

            android:layout_height="wrap_content"

            android:layout_margin="5dp"

            android:background="@drawable/option"

            android:gravity="center"

            android:text="@string/option_1"

            android:textSize="18sp"

            android:textStyle="bold" />

    <TextView

            android:id="@+id/option_2"

            android:layout_width="fill_parent"

            android:layout_height="wrap_content"

            android:layout_margin="5dp"

            android:background="@drawable/option"

            android:gravity="center"

            android:text="@string/option_2"

            android:textSize="18sp"

            android:textStyle="bold" />

 

    <TextView

            android:id="@+id/choice_1"

            android:layout_width="fill_parent"

            android:layout_height="wrap_content"

            android:layout_margin="5dp"

            android:background="@drawable/choice"

            android:gravity="center"

            android:textSize="18sp"

            android:text="@string/choice_1" />

    <TextView

            android:id="@+id/choice_2"

            android:layout_width="fill_parent"

            android:layout_height="wrap_content"

            android:layout_margin="5dp"

            android:background="@drawable/choice"

            android:gravity="center"

            android:textSize="18sp"

            android:text="@string/choice_2" />

</LinearLayout>

The following will be the output of your layout:

DragAndroid2.jpg

Step 5:

Open your "Activity" class. First we use a resource id and reference it to the views.

First we define:

private TextView option1, option2, choice1, choice2;
Inside onCreate(), write following code.
//views to drag
option1 = (TextView)findViewById(R.id.option_1);
option2 = (TextView)findViewById(R.id.option_2);

//views to drop onto
choice1 = (TextView)findViewById(R.id.choice_1);
choice2 = (TextView)findViewById(R.id.choice_2);

Your project structure will look like:

DragAndroid3.jpg

Step 6:

The references to layout ids are now done. We will add "TouchListener" to our activity.
 

private final class ChoiceTouchListener implements View.OnTouchListener {

    @Override

    public boolean onTouch(View view, MotionEvent motionEvent) {

       if (motionEvent.getAction() == MotionEvent.ACTION_DOWN) {

            //setup drag

            return true;

        }

        else {

            return false;

        }

    }

}

We are only interested in cases where the user has touched the View to drag it, so inside the if statement we will setup the drag operation before the "return true" statement.

//setup drag
ClipData data = ClipData.newPlainText("", "");
View.DragShadowBuilder shadowBuilder = new View.DragShadowBuilder(view);

//start dragging the item touched
view.startDrag(data, shadowBuilder, view, 0);

Step 7:

We have created a class that will handle the Touch Event and if the Touch Event is "Down" then we have written the code for startiing the dragging of the particular view on the touch that is to be performed.

We now need to write some short code to handle the Drag event. So write the following code.
 

private class ChoiceDragListener implements View.OnDragListener {

    @Override

    public boolean onDrag(View v, DragEvent dragEvent) {

    switch (dragEvent.getAction()) {

        case DragEvent.ACTION_DRAG_STARTED:

            //no action necessary

            break;

        case DragEvent.ACTION_DRAG_ENTERED:

            //no action necessary

            break;

        case DragEvent.ACTION_DRAG_EXITED:

            //no action necessary

            break;

        case DragEvent.ACTION_DROP:

            //handle the dragged view being dropped over a drop view

            View view = (View) dragEvent.getLocalState();

            //stop displaying the view where it was before it was dragged

            view.setVisibility(View.INVISIBLE);

            //view dragged item is being dropped on

            TextView dropTarget = (TextView) v;

            //view being dragged and dropped

            TextView dropped = (TextView) view;

            //update the text in the target view to reflect the data being dropped

            dropTarget.setText(dropped.getText());

            //make it bold to highlight the fact that an item has been dropped

                    dropTarget.setTypeface(Typeface.DEFAULT_BOLD);

                    //if an item has already been dropped here, there will be a tag

                    Object tag = dropTarget.getTag();

                    //if there is already an item here, set it back visible in its original place

                    if(tag!=null)

                    {

                        //the tag is the view id already dropped here

                        int existingID = (Integer)tag;

                        //set the original view visible again

                        findViewById(existingID).setVisibility(View.VISIBLE);

                    }

                    //set the tag in the target view being dropped on - to the ID of the view being dropped

                    dropTarget.setTag(dropped.getId());

 

                    break;

                case DragEvent.ACTION_DRAG_ENDED:

                    //no action necessary

                    break;

                default:

                    break;

            }

            return true;

        }

    }

Step 8:

Add listeners to views. Once again go to "onCreate()" and after the reference of to the views, add the following code.

//set touch listeners
option1.setOnTouchListener(new ChoiceTouchListener());
option2.setOnTouchListener(new ChoiceTouchListener());

//set drag listeners
choice1.setOnDragListener(new ChoiceDragListener());
choice2.setOnDragListener(new ChoiceDragListener());

Step 9:

You are done with your coding. What you need to do is just run the application. When you see your application in an emulator or in a device:

DragAndroid4.jpg

Click on the "Mahesh Chand" text view, and drag it to "Founder and Editor-in-Chief" and Drop it there. Perform the same action for "Praveen Kumar".

DragAndroid5.jpg

DragAndroid6.jpg

DragAndroid7.jpg

Summary

Today we learned how to use Drag & Drop functionality of Android SDK. This is a very good feature provided by Android. We can also apply this functionality in other game development applications.
 

Up Next
    Ebook Download
    View all
    Learn
    View all