Skip to main content

How to implement drag-and-drop functionality in a ListView in Kotlin Android

How to implement drag-and-drop functionality in a ListView in Kotlin Android.

Here's a step-by-step tutorial on how to implement drag-and-drop functionality in a ListView in Kotlin Android:

Step 1: Set up the project

  1. Create a new Android project in Android Studio.
  2. Open the build.gradle file (Module-level) and add the following dependency:
    implementation 'com.android.support:recyclerview-v7:28.0.0'

Step 2: Create the layout file

  1. Open the activity_main.xml layout file and add a ListView and a TextView as follows:

    <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingLeft="16dp"
    android:paddingTop="16dp"
    android:paddingRight="16dp"
    android:paddingBottom="16dp"
    tools:context=".MainActivity">

    <ListView
    android:id="@+id/listView"
    android:layout_width="match_parent"
    android:layout_height="wrap_content" />

    <TextView
    android:id="@+id/textView"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_below="@id/listView"
    android:layout_centerHorizontal="true"
    android:paddingTop="16dp"
    android:text="Drag and Drop Items"
    android:textSize="18sp" />

    </RelativeLayout>

Step 3: Create the custom adapter

  1. Create a new Kotlin class called CustomAdapter and extend it from BaseAdapter.

  2. Override the necessary methods (getCount(), getItem(), getItemId(), and getView()) to populate the ListView.

  3. Add a method called swapItems() that will be used to swap the positions of items in the ListView.

    class CustomAdapter(private val itemList: ArrayList<String>) : BaseAdapter() {

    override fun getCount(): Int {
    return itemList.size
    }

    override fun getItem(position: Int): Any {
    return itemList[position]
    }

    override fun getItemId(position: Int): Long {
    return position.toLong()
    }

    override fun getView(position: Int, convertView: View?, parent: ViewGroup?): View {
    val view = convertView ?: LayoutInflater.from(parent?.context).inflate(android.R.layout.simple_list_item_1, parent, false)
    val textView = view.findViewById<TextView>(android.R.id.text1)
    textView.text = itemList[position]
    return view
    }

    fun swapItems(fromPosition: Int, toPosition: Int) {
    val item = itemList[fromPosition]
    itemList.removeAt(fromPosition)
    itemList.add(toPosition, item)
    notifyDataSetChanged()
    }
    }

Step 4: Implement drag-and-drop functionality

  1. Open the MainActivity.kt file and add the following code:

    class MainActivity : AppCompatActivity() {

    private var itemList: ArrayList<String> = ArrayList()

    override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_main)

    // Initialize the itemList
    itemList.add("Item 1")
    itemList.add("Item 2")
    itemList.add("Item 3")
    itemList.add("Item 4")
    itemList.add("Item 5")

    // Create the custom adapter and set it to the ListView
    val adapter = CustomAdapter(itemList)
    listView.adapter = adapter

    // Enable drag-and-drop functionality on the ListView
    listView.setOnItemLongClickListener { _, view, position, _ ->
    val data = ClipData.newPlainText("", "")
    val shadowBuilder = View.DragShadowBuilder(view)
    view.startDrag(data, shadowBuilder, view, 0)
    true
    }

    listView.setOnDragListener { _, event ->
    when (event.action) {
    DragEvent.ACTION_DRAG_STARTED -> true
    DragEvent.ACTION_DRAG_ENTERED -> true
    DragEvent.ACTION_DRAG_LOCATION -> true
    DragEvent.ACTION_DRAG_EXITED -> true
    DragEvent.ACTION_DROP -> {
    val itemPosition = event.localState as View
    val toPosition = listView.pointToPosition(event.x.toInt(), event.y.toInt())
    adapter.swapItems(itemPosition.tag as Int, toPosition)
    true
    }
    DragEvent.ACTION_DRAG_ENDED -> true
    else -> false
    }
    }
    }
    }

Step 5: Run the app

  1. Run the app on an emulator or a physical device.
  2. Long press an item in the ListView and drag it to a different position.
  3. The items should be swapped when you drop the item.

That's it! You have successfully implemented drag-and-drop functionality in a ListView in Kotlin Android.