Skip to main content

How to implement drag and drop functionality with a Spinner in Kotlin Android

How to implement drag and drop functionality with a Spinner in Kotlin Android.

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

  1. Create a new project in Android Studio and set up the basic layout and dependencies.
  2. Open the layout file for your activity and add a Spinner view. You can do this by adding the following code snippet:
<Spinner
android:id="@+id/spinner"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="16dp" />
  1. In the activity class, initialize the Spinner and populate it with data. You can do this by adding the following code snippet:
val spinner: Spinner = findViewById(R.id.spinner)
val data = listOf("Item 1", "Item 2", "Item 3", "Item 4")
val adapter = ArrayAdapter(this, android.R.layout.simple_spinner_item, data)
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item)
spinner.adapter = adapter
  1. Implement the drag and drop functionality by creating a custom Spinner class that extends the default Spinner class. Add the following code snippet:
class DragDropSpinner(context: Context, attrs: AttributeSet) : Spinner(context, attrs) {
private var dragStartPosition = -1

override fun onTouchEvent(event: MotionEvent): Boolean {
when (event.action) {
MotionEvent.ACTION_DOWN -> {
dragStartPosition = pointToPosition(event.x.toInt(), event.y.toInt())
startDrag(ClipData.newPlainText("", ""), DragShadowBuilder(this), this, 0)
return true
}
}
return super.onTouchEvent(event)
}
}
  1. Update the layout file to use the custom Spinner class. Replace the existing Spinner view with the following code snippet:
<com.example.myapp.DragDropSpinner
android:id="@+id/spinner"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="16dp" />
  1. In the activity class, replace the Spinner initialization code with the following code snippet:
val spinner: DragDropSpinner = findViewById(R.id.spinner)
  1. Finally, handle the drag and drop events in the activity class. Add the following code snippet:
spinner.setOnDragListener { _, event ->
when (event.action) {
DragEvent.ACTION_DROP -> {
val draggedItemPosition = event.localState as Int
val droppedItemPosition = spinner.pointToPosition(event.x.toInt(), event.y.toInt())
val adapter = spinner.adapter as ArrayAdapter<String>
val draggedItem = adapter.getItem(draggedItemPosition)
adapter.remove(draggedItem)
adapter.insert(draggedItem, droppedItemPosition)
adapter.notifyDataSetChanged()
return@setOnDragListener true
}
}
false
}

That's it! You have successfully implemented drag and drop functionality with a Spinner in Kotlin Android. Now you can drag and drop items within the Spinner to reorder them.