From 141eff88414c82dad6f6818ca79efcda024ac9f1 Mon Sep 17 00:00:00 2001 From: iKirby <6316115+iKirby@users.noreply.github.com> Date: Fri, 6 Oct 2023 13:09:03 +0800 Subject: [PATCH] Fix profile order --- .../sfa/ui/main/ConfigurationFragment.kt | 49 +++++++++++-------- 1 file changed, 28 insertions(+), 21 deletions(-) diff --git a/app/src/main/java/io/nekohasekai/sfa/ui/main/ConfigurationFragment.kt b/app/src/main/java/io/nekohasekai/sfa/ui/main/ConfigurationFragment.kt index 7c19016..8b44e32 100644 --- a/app/src/main/java/io/nekohasekai/sfa/ui/main/ConfigurationFragment.kt +++ b/app/src/main/java/io/nekohasekai/sfa/ui/main/ConfigurationFragment.kt @@ -26,6 +26,7 @@ import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.GlobalScope import kotlinx.coroutines.launch import kotlinx.coroutines.withContext +import java.util.Collections class ConfigurationFragment : Fragment() { @@ -53,6 +54,16 @@ class ConfigurationFragment : Fragment() { override fun onSwiped(viewHolder: RecyclerView.ViewHolder, direction: Int) { } + + override fun onSelectedChanged( + viewHolder: RecyclerView.ViewHolder?, + actionState: Int + ) { + super.onSelectedChanged(viewHolder, actionState) + if (actionState == ItemTouchHelper.ACTION_STATE_IDLE) { + adapter.updateUserOrder() + } + } }).attachToRecyclerView(it) } adapter.reload() @@ -85,10 +96,8 @@ class ConfigurationFragment : Fragment() { RecyclerView.Adapter() { internal var items: MutableList = mutableListOf() - private var isMoving = false internal fun reload() { - if (isMoving) return scope.launch(Dispatchers.IO) { val newItems = ProfileManager.list().toMutableList() withContext(Dispatchers.Main) { @@ -106,30 +115,28 @@ class ConfigurationFragment : Fragment() { } internal fun move(from: Int, to: Int): Boolean { - val first = items.getOrNull(from) ?: return false - var previousOrder = first.userOrder - val (step, range) = if (from < to) Pair(1, from until to) else Pair( - -1, to + 1 downTo from - ) - val updated = mutableListOf() - for (i in range) { - val next = items.getOrNull(i + step) ?: return false - val order = next.userOrder - next.userOrder = previousOrder - previousOrder = order - updated.add(next) + if (from < to) { + for (i in from until to) { + Collections.swap(items, i, i + 1) + } + } else { + for (i in from downTo to + 1) { + Collections.swap(items, i, i - 1) + } } - first.userOrder = previousOrder - updated.add(first) notifyItemMoved(from, to) - isMoving = true - GlobalScope.launch(Dispatchers.IO) { - ProfileManager.update(updated) - isMoving = false - } return true } + internal fun updateUserOrder() { + items.forEachIndexed { index, profile -> + profile.userOrder = index.toLong() + } + GlobalScope.launch(Dispatchers.IO) { + ProfileManager.update(items) + } + } + override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): Holder { return Holder( this,