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
- Create a new Android project in Android Studio.
- Open the
build.gradlefile (Module-level) and add the following dependency:implementation 'com.android.support:recyclerview-v7:28.0.0'
Step 2: Create the layout file
Open the
activity_main.xmllayout file and add aListViewand aTextViewas 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
Create a new Kotlin class called
CustomAdapterand extend it fromBaseAdapter.Override the necessary methods (
getCount(),getItem(),getItemId(), andgetView()) to populate the ListView.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
Open the
MainActivity.ktfile 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
- Run the app on an emulator or a physical device.
- Long press an item in the ListView and drag it to a different position.
- 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.