ProAndroidDev

The latest posts from Android Professionals and Google Developer Experts.

Follow publication

Drag and drop in Android. All you need to know

--

Have you ever been in a situation where you needed to create an Android app with drag and drop feature? I was. And if you were too, I know what you might feel right now, believe me. At the beginning it will look like something very complicated with calculations of touches, drags, movement of the objects and many things like that 🤪, but in reality, there is a very nice API in the Android Framework, so we just need to use it 😌. Let’s see how it works in reality.

Image from Dribbble ( https://dribbble.com/shots/6305593-Interaction-Designers)

Let’s create a simple app, where we will have random words, and from those words we will create a sentence. Each word will be represented as a box, and by dragging and dropping we will form our sentence. So, from the UI point of view, there should be two Recycler Views. One for mixed words, second for a sentence (ordered words).

Basically, this is how our app will look like.

Huh, nice one!

Let’s bring some magic here!

We have two components. The first one is from where the items will be dragged, and the second — where will be dropped.

Let’s start from the first one. In the demo project, drag will start on a long click on each recycler view item. So, in the adapter’s view holder, let’s add a LongClickListener to each item.

Here, the instance of ClipData is a simple data about the draggable item, and the DragShadowBuilder is the image, represented to a user during the drag process.

Now we can drag words, but we can’t drop them.

To be able to drop, let’s implement a DragListener

… and apply it to sentence recycler view.

What’s next?

Nothing!

Yeah, this is all you need. The basic stuff to implement a simple drag and drop in any Android application. You can add more tweaks to make the drag and drop process more suitable for your application.

I’ve created a demo project, which may be useful, if this guide is not enough for you or you’re just lazy, and the only thing you want to read is a code.

Click to open demo

Read some documentation

Happy coding!

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

--

--

Published in ProAndroidDev

The latest posts from Android Professionals and Google Developer Experts.

Written by Robert Levonyan

Senior Android Developer @Picsart. Find my projects here: https://robertlevonyan.com

Responses (1)

Write a response