Skip to content

Commit

Permalink
优化
Browse files Browse the repository at this point in the history
  • Loading branch information
821938089 committed Jan 27, 2025
1 parent 63a6450 commit 13cd03b
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 0 deletions.
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package io.legado.app.base.adapter

import android.content.Context
import android.os.Parcelable
import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.recyclerview.widget.AsyncListDiffer
Expand All @@ -23,17 +24,26 @@ abstract class DiffRecyclerAdapter<ITEM, VB : ViewBinding>(protected val context
AsyncListDiffer(this, diffItemCallback).apply {
addListListener { _, _ ->
onCurrentListChanged()
if (keepScrollPosition) {
layoutManager?.onRestoreInstanceState(layoutState)
layoutState = null
}
}
}
}

private var itemClickListener: ((holder: ItemViewHolder, item: ITEM) -> Unit)? = null
private var itemLongClickListener: ((holder: ItemViewHolder, item: ITEM) -> Boolean)? = null

private var layoutManager: RecyclerView.LayoutManager? = null
private var layoutState: Parcelable? = null

var itemAnimation: ItemAnimation? = null

abstract val diffItemCallback: DiffUtil.ItemCallback<ITEM>

open val keepScrollPosition = false

fun setOnItemClickListener(listener: (holder: ItemViewHolder, item: ITEM) -> Unit) {
itemClickListener = listener
}
Expand All @@ -48,6 +58,9 @@ abstract class DiffRecyclerAdapter<ITEM, VB : ViewBinding>(protected val context

fun setItems(items: List<ITEM>?) {
kotlin.runCatching {
if (keepScrollPosition) {
layoutState = layoutManager?.onSaveInstanceState()
}
asyncListDiffer.submitList(items?.toMutableList())
}
}
Expand Down Expand Up @@ -161,6 +174,7 @@ abstract class DiffRecyclerAdapter<ITEM, VB : ViewBinding>(protected val context
override fun onAttachedToRecyclerView(recyclerView: RecyclerView) {
super.onAttachedToRecyclerView(recyclerView)
val manager = recyclerView.layoutManager
layoutManager = manager
if (manager is GridLayoutManager) {
manager.spanSizeLookup = object : GridLayoutManager.SpanSizeLookup() {
override fun getSpanSize(position: Int): Int {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,8 @@ import io.legado.app.utils.visible
class SearchAdapter(context: Context, val callBack: CallBack) :
DiffRecyclerAdapter<SearchBook, ItemSearchBinding>(context) {

override val keepScrollPosition = true

override val diffItemCallback: DiffUtil.ItemCallback<SearchBook>
get() = object : DiffUtil.ItemCallback<SearchBook>() {

Expand Down

0 comments on commit 13cd03b

Please sign in to comment.