Skip to content

Instantly share code, notes, and snippets.

@vlkam
Created January 4, 2021 10:46
Show Gist options
  • Save vlkam/0e92d682ca117e7cac5f2464242076f1 to your computer and use it in GitHub Desktop.
Save vlkam/0e92d682ca117e7cac5f2464242076f1 to your computer and use it in GitHub Desktop.
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