I was trying to use setPeekHeight method on MaterialDialog(context, BottomSheet()) but the method accepts only literal px or a resource, but passing them requires knowing the final height of the BottomSheet.
Is there a way to pass a percentage value to the method? For example, I want my view to be 80% of the total screen height so I can call setPeekHeight(percentage=80)
I've noticed that in the code this mechanism is used to default the height to 60%, so maybe this can be extended to everyone if it's not already present.
If you are using Kotlin you can measure the height of the view you want to use as peek. Just use this inline function:
Then on your view:
yourView.afterMeasured {
bottom sheet.setPeekHeight(height)
}
Like this:
I don't think there's an easy way to do that. You need to measure the view's height.
Your answer works great but in my case, the MaterialDialog is implemented in a class itself and needs to be used by many classes, so I didn't want to make it view dependant, and since I needed a fraction of the total screen size, at the end I settled for using display metrics:
init {
val peekHeight = context.resources.displayMetrics.heightPixels * 70 / 100
dialog.setPeekHeight(peekHeight)
// ...
}
Originally I've tried this approach, but I was passing to setPeekHeight() a value un Dp, only today I realized that it needed a Px, and solved this.
I've written an extension function to do this more easily, this gets the size of the screen from Window object stored inside MaterialDialog in the same way the library does this
/**
* Let the user set [BottomSheet]'s peek height based on a percentage value
*
* @param percentage percentage of the screen size
* @receiver MaterialDialog
* @return MaterialDialog
*/
private fun MaterialDialog.setPeekHeight(percentage: Int): MaterialDialog {
require(percentage in 0..100) { "This is not a percentage value!" }
val size = Point()
this.window?.windowManager?.defaultDisplay?.getSize(size)
this.setPeekHeight(literal = size.y * percentage / 100)
return this
}
I do not plan to allow percentage values to be given - it's better to use a dimension resource that is different based on screen size by overriding dimens.xml for different screen widths.
Most helpful comment
Your answer works great but in my case, the MaterialDialog is implemented in a class itself and needs to be used by many classes, so I didn't want to make it view dependant, and since I needed a fraction of the total screen size, at the end I settled for using display metrics:
Originally I've tried this approach, but I was passing to
setPeekHeight()a value un Dp, only today I realized that it needed a Px, and solved this.Edit
I've written an extension function to do this more easily, this gets the size of the screen from
Windowobject stored insideMaterialDialogin the same way the library does this