Skip to content

Instantly share code, notes, and snippets.

@StanGenchev
Last active December 4, 2019 12:09
Show Gist options
  • Save StanGenchev/6fbc66fc620e441d4e68e14cb3607530 to your computer and use it in GitHub Desktop.
Save StanGenchev/6fbc66fc620e441d4e68e14cb3607530 to your computer and use it in GitHub Desktop.
GridLayoutManager 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 NotifyingGridLayoutManager(context: Context?) : GridLayoutManager(context, 1) {
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 = NotifyingGridLayoutManager(context)
layout.spanCount = 2
layout.onLayoutCompleteCallback = onLayoutCompleted(layout)
...
}
// Turns off nested scrolling if the items in RecyclerView are all visible.
// This way, your Appbar/BottomNavigation/Fab won't scroll away if it is not needed.
private fun onLayoutCompleted(layout: NotifyingGridLayoutManager): 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