Skip to content

Instantly share code, notes, and snippets.

@macsystems
Created January 19, 2020 14:35
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save macsystems/71f2700280feab0133e001382ea6f615 to your computer and use it in GitHub Desktop.
Save macsystems/71f2700280feab0133e001382ea6f615 to your computer and use it in GitHub Desktop.
Extension for BottomSheet.BottomSheetBehavior which invokes an function when sheet is collapsed, this can be useful is the sheet need to display new data
/**
* Call to populate new data for Bottomsheet.
* If Bottomsheet is shown it will collapse first, then it will invoke doWhenCollapsed
*/
inline fun <reified T : View> BottomSheetBehavior<T>.colapseAndShow(noinline doWhenCollapsed: () -> Unit) {
when (state) {
STATE_EXPANDED,
STATE_HALF_EXPANDED -> {
addBottomSheetCallback(WaitForCollapsedState(this, doWhenCollapsed))
return // don't change state again for following conditions
}
STATE_COLLAPSED,
STATE_HIDDEN -> {
doWhenCollapsed()
state = BottomSheetBehavior.STATE_EXPANDED
return
}
}
}
/**
* Callback handler which waits until sheet is collapsed to invoke function
*/
class WaitForCollapsedState<T : View>(
private val bottomSheet: BottomSheetBehavior<T>,
private val doWhenCollapsed: () -> Unit
) :
BottomSheetBehavior.BottomSheetCallback() {
init {
bottomSheet.state = STATE_COLLAPSED
}
override fun onSlide(bottomSheet: View, slideOffset: Float) {
// ignore
}
override fun onStateChanged(view: View, newState: Int) {
when (newState) {
STATE_EXPANDED,
STATE_HALF_EXPANDED,
STATE_HIDDEN,
STATE_DRAGGING,
STATE_SETTLING -> {
// do nothing
}
STATE_COLLAPSED -> {
bottomSheet.removeBottomSheetCallback(this)
doWhenCollapsed()
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment