Created
January 4, 2021 10:46
-
-
Save vlkam/0e92d682ca117e7cac5f2464242076f1 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
open class LinearLayoutManagerExt @JvmOverloads constructor ( | |
val name : String, | |
val fragment: Fragment, | |
val adapter : RecyclerView.Adapter<out RecyclerView.ViewHolder>, | |
attrs : AttributeSet? = null, | |
defStyleAttr : Int = 0, | |
defStyleRes : Int = 0 | |
) : LinearLayoutManager(fragment.requireContext(),attrs,defStyleAttr,defStyleRes){ | |
protected var savedState : SavedState? = fragment.arguments?.getParcelable<SavedState?>(name) | |
protected val lifecycleObserver = object : LifecycleEventObserver { | |
override fun onStateChanged(source: LifecycleOwner, event: Lifecycle.Event) { | |
when (event) { | |
Lifecycle.Event.ON_PAUSE -> { | |
val parc = onSaveInstanceState() | |
if (fragment.arguments == null) { | |
fragment.arguments = Bundle() | |
} | |
fragment.arguments?.putParcelable(name, parc) | |
fragment.lifecycle.removeObserver(this) | |
} | |
} | |
} | |
} | |
protected val adapterDataObserver = object : RecyclerView.AdapterDataObserver() { | |
override fun onItemRangeInserted(positionStart: Int, itemCount: Int) { | |
if(savedState != null && itemCount > 0){ | |
onRestoreInstanceState(savedState) | |
savedState = null | |
} | |
if(itemCount > 0){ | |
adapter.unregisterAdapterDataObserver(this) | |
} | |
} | |
} | |
init { | |
fragment.lifecycle.addObserver(lifecycleObserver) | |
adapter.registerAdapterDataObserver(adapterDataObserver ) | |
} | |
override fun onDetachedFromWindow(view: RecyclerView?, recycler: RecyclerView.Recycler?) { | |
super.onDetachedFromWindow(view, recycler) | |
try{ | |
adapter.unregisterAdapterDataObserver(adapterDataObserver ) | |
} catch (_ : Exception){} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment