Android uses recyclerview to realize icon drag and drop sorting and addition and deletion management

Time:2022-5-10
catalogue
  • 1. Renderings
  • 2. Basic functions
  • 3. Realization ideas
    • 1. The status of each application icon is represented by enumeration option
    • 2. Create an itemtouchhelper object in editing status and attach it to recyclerview
    • 3. When the application icon is deleted from the top, you need to add it to the bottom and reset it to the addable state

1. Renderings

2. Basic functions

In the non editing state, you can directly click the icon to jump
In editing status, you can drag, add and delete
Those that have been added cannot be added again

3. Realization ideas

It is implemented with two recyclerviews and maintains two data sources at the same time. The upper part is a common application, with a maximum of 8; The lower part is all applications.

1. The status of each application icon is represented by enumeration option

//Current operation status
enum class Option {
 ADD, REMOVE, NONE
}

2. Create an itemtouchhelper object in editing status and attach it to recyclerview


if (enable) {
 itemTouchHelper.attachToRecyclerView(binding.rvApps)
} 

Among them, in the implementation of itemtouchhelper In the onmove() function of the callback interface, it means that the user has raised his hand and the icon position has changed. At this time, synchronize the order of the icons on the interface back to the data source of the adapter:


val newData = mutableListOf<Pair<String, Int>>()
commonAppsAdapter.data.forEachIndexed { index, _ ->
 val holder = recyclerView.findViewHolderForAdapterPosition(index) as AppsHolder
 newData.add(Pair(holder.funcUrl, index))
}
for (i in newData) {
  val sameFuncIndex = commonAppsAdapter.data.indexOfFirst { i.first == it.uid }
  Collections.swap(commonAppsAdapter.data, i.second, sameFuncIndex)
}

3. When the application icon is deleted from the top, you need to add it to the bottom and reset it to the addable state


commonAppsAdapter.onRemoveBtnClickListener = object : OnRemoveBtnClickListener {
 override fun onClick(view: View, appBean: AppBean) {
  val theSameElementIndex = allAppsAdapter.data.indexOfFirst { it.uid == appBean.uid }
  if (theSameElementIndex < 0) return
  allAppsAdapter.data[theSameElementIndex].option = AppBean.Companion.Option.ADD
  allAppsAdapter.notifyItemChanged(theSameElementIndex)
 }
}

Source code, please go to GitHub

The above is the details of Android’s icon drag and drop sorting and addition and deletion management with recyclerview. For more information about Android’s icon drag and drop sorting and addition and deletion management, please pay attention to other relevant articles of developeppaer!