Fix profile order

This commit is contained in:
iKirby
2023-10-06 13:09:03 +08:00
committed by GitHub
parent fcafd5f956
commit 141eff8841

View File

@@ -26,6 +26,7 @@ import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.GlobalScope import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext import kotlinx.coroutines.withContext
import java.util.Collections
class ConfigurationFragment : Fragment() { class ConfigurationFragment : Fragment() {
@@ -53,6 +54,16 @@ class ConfigurationFragment : Fragment() {
override fun onSwiped(viewHolder: RecyclerView.ViewHolder, direction: Int) { 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) }).attachToRecyclerView(it)
} }
adapter.reload() adapter.reload()
@@ -85,10 +96,8 @@ class ConfigurationFragment : Fragment() {
RecyclerView.Adapter<Holder>() { RecyclerView.Adapter<Holder>() {
internal var items: MutableList<Profile> = mutableListOf() internal var items: MutableList<Profile> = mutableListOf()
private var isMoving = false
internal fun reload() { internal fun reload() {
if (isMoving) return
scope.launch(Dispatchers.IO) { scope.launch(Dispatchers.IO) {
val newItems = ProfileManager.list().toMutableList() val newItems = ProfileManager.list().toMutableList()
withContext(Dispatchers.Main) { withContext(Dispatchers.Main) {
@@ -106,30 +115,28 @@ class ConfigurationFragment : Fragment() {
} }
internal fun move(from: Int, to: Int): Boolean { internal fun move(from: Int, to: Int): Boolean {
val first = items.getOrNull(from) ?: return false if (from < to) {
var previousOrder = first.userOrder for (i in from until to) {
val (step, range) = if (from < to) Pair(1, from until to) else Pair( Collections.swap(items, i, i + 1)
-1, to + 1 downTo from }
) } else {
val updated = mutableListOf<Profile>() for (i in from downTo to + 1) {
for (i in range) { Collections.swap(items, i, i - 1)
val next = items.getOrNull(i + step) ?: return false }
val order = next.userOrder
next.userOrder = previousOrder
previousOrder = order
updated.add(next)
} }
first.userOrder = previousOrder
updated.add(first)
notifyItemMoved(from, to) notifyItemMoved(from, to)
isMoving = true
GlobalScope.launch(Dispatchers.IO) {
ProfileManager.update(updated)
isMoving = false
}
return true 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 { override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): Holder {
return Holder( return Holder(
this, this,