Created
March 28, 2019 09:45
-
-
Save rizafu/e7d3b86a4eb2156140b1aedaa36d4208 to your computer and use it in GitHub Desktop.
Android bottom sheet behavior in bottom sheet dialog fragment
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
abstract class BottomSheetBehaviorDialogFragment: BottomSheetDialogFragment(){ | |
private var behavior: BottomSheetBehavior<View>? = null | |
abstract fun createContentView(): View | |
open fun getStateStart(): Int = BottomSheetBehavior.STATE_EXPANDED | |
open fun onSlide(bottomSheet: View, slideOffset: Float) = Unit | |
open fun onStateChanged(bottomSheet: View, newState: Int) = Unit | |
open fun setupBehavior(behavior: BottomSheetBehavior<View>) = Unit | |
open fun isBackgroundTransparent() = false | |
fun getBehavior() = behavior | |
override fun getTheme(): Int = if (isBackgroundTransparent()) R.style.BottomSheetDialogTransparent else super.getTheme() | |
override fun onStart() { | |
super.onStart() | |
behavior?.state = getStateStart() | |
} | |
override fun onCreateDialog(savedInstanceState: Bundle?): Dialog { | |
val dialog = super.onCreateDialog(savedInstanceState) as BottomSheetDialog | |
val contentView = createContentView() | |
dialog.setContentView(contentView) | |
behavior = BottomSheetBehavior.from(contentView.parent as View)?.also { | |
setupBehavior(it) | |
it.setBottomSheetCallback(object: BottomSheetBehavior.BottomSheetCallback(){ | |
override fun onSlide(bottomSheet: View, slideOffset: Float) { | |
this@BottomSheetBehaviorDialogFragment.onSlide(bottomSheet, slideOffset) | |
} | |
override fun onStateChanged(bottomSheet: View, newState: Int) { | |
if (newState == BottomSheetBehavior.STATE_HIDDEN) { | |
dismissAllowingStateLoss() | |
} else { | |
this@BottomSheetBehaviorDialogFragment.onStateChanged(bottomSheet, newState) | |
} | |
} | |
}) | |
} | |
return dialog | |
} | |
} |
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
<resources> | |
<style name="BottomSheetTransparent" parent="@style/Widget.Design.BottomSheet.Modal"> | |
<item name="android:background">@android:color/transparent</item> | |
</style> | |
<style name="BottomSheetDialogTransparent" parent="@style/Theme.Design.Light.BottomSheetDialog"> | |
<item name="bottomSheetStyle">@style/BottomSheetTransparent</item> | |
</style> | |
</resources> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment