When using the itemTouchHelper onMove method. How can you while using a numbered list based on the position in the list.
For example, item 1, item 2, item 3, etc. all based on the actual position in the list the item is in. How can you then when moving the item by dragging it up or down. Update the rest of the items in the list to reflect the proper position in the list it’s in?
I'm using the below code:
override fun onMove(recyclerView: RecyclerView, viewHolder: RecyclerView.ViewHolder, target: RecyclerView.ViewHolder): Boolean {
val fromPosition = viewHolder.adapterPosition
val toPosition = target.adapterPosition
Collections.swap(steps!!, fromPosition, toPosition)
recyclerView.adapter!!.notifyItemMoved(fromPosition,toPosition)
return true
}
Snippet:
Video:
UPDATE (Adapter code):
val TAG:String = "StepAdapter"
var steps: MutableList<Step> = ArrayList()
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): StepViewHolder {
return StepViewHolder(
LayoutInflater.from(parent.context)
.inflate(R.layout.recipe_property_step_list_item, parent, false))
}
override fun getItemCount(): Int{
return steps.size
}
override fun onBindViewHolder(holder: StepViewHolder, position: Int) {
holder.bind(steps.get(position), position)
Log.i(TAG,"onBindViewHolder - ${steps.get(position)}")
}
override fun onBindViewHolder(holder: StepViewHolder, position: Int, payloads: MutableList<Any>) {
Log.i(TAG,"onBindViewHolder - Payloads - $payloads")
val text:String = StringBuilder("${position + 1}.) ${steps[position].text}").toString()
Log.i(TAG,"onBindViewHolder - Text - $text")
holder.st_text.text = text
}
fun updateSteps(newSteps: MutableList<Step>){
val diffResult = DiffUtil.calculateDiff(StepDiffCallBack(this.steps,newSteps))
this.steps.clear()
this.steps.addAll(newSteps)
notifyDataSetChanged()
diffResult.dispatchUpdatesTo(this)
}
LOGS:
2020-04-12 16:57:21.787 15808-15808/com.keep.recipeapp I/StepAdapter: onBindViewHolder - Payloads - []
2020-04-12 16:57:21.787 15808-15808/com.keep.recipeapp I/StepAdapter: onBindViewHolder - Text - 1.) Prepping the kitchen sink
2020-04-12 16:57:21.789 15808-15808/com.keep.recipeapp I/StepAdapter: onBindViewHolder - Payloads - []
2020-04-12 16:57:21.789 15808-15808/com.keep.recipeapp I/StepAdapter: onBindViewHolder - Text - 2.) prep the nuts and bolts
2020-04-12 16:57:21.791 15808-15808/com.keep.recipeapp I/StepAdapter: onBindViewHolder - Payloads - []
2020-04-12 16:57:21.791 15808-15808/com.keep.recipeapp I/StepAdapter: onBindViewHolder - Text - 3.) Cook the kitchen sink
TEST DATA