Last active
December 4, 2019 12:10
-
-
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.
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
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 | |
} |
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
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()) | |
} | |
} | |
} |
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
interface OnLayoutCompleteCallback { | |
fun onLayoutComplete() | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment