Skip to content

Instantly share code, notes, and snippets.

@StanGenchev
Last active December 4, 2019 12:10
Show Gist options
  • Save StanGenchev/20cdb0f27ee55eec05aa1511906ddedc to your computer and use it in GitHub Desktop.
Save StanGenchev/20cdb0f27ee55eec05aa1511906ddedc to your computer and use it in GitHub Desktop.
LinearLayoutManager with 'onLayoutCompleted' callback. You can use this to execute code after the layout has finished drawing on the screen. You can also use 'isLastItemCompletelyVisible' to enable/disable the nested scrolling, for a better experience with Appbars who have 'appbar_scrolling_view_behavior"' set.
class NotifyingLinearLayoutManager(context: Context?) : LinearLayoutManager(context, VERTICAL, false) {
var onLayoutCompleteCallback: OnLayoutCompleteCallback? = null
override fun onLayoutCompleted(state: RecyclerView.State?) {
super.onLayoutCompleted(state)
onLayoutCompleteCallback?.onLayoutComplete()
}
fun isLastItemCompletelyVisible() = findLastCompletelyVisibleItemPosition() == itemCount - 1
}
override fun onCreateView(...): View? {
...
val layout = NotifyingLinearLayoutManager(context)
layout.onLayoutCompleteCallback = onLayoutCompleted(layout)
...
}
// Turns off nested scrolling if the items in the RecyclerView are all visible.
// This way, your Appbar/BottomNavigation/Fab won't scroll away if it is not needed.
private fun onLayoutCompleted(layout: NotifyingLinearLayoutManager): OnLayoutCompleteCallback? {
return object : OnLayoutCompleteCallback {
override fun onLayoutComplete() {
recyclerView.isNestedScrollingEnabled = !(layout.isLastItemCompletelyVisible())
}
}
}
interface OnLayoutCompleteCallback {
fun onLayoutComplete()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment