I want to design a layout composed from: a toolbar at the top of the layout (which should take 20% of the screen), then, vertically,underneath, a ViewPager (which should take 60% of the screen) and then, still vertically underneath, a BottomSheet (which should take 20% of the screen when it is collapsed and to take 100% of the screen when it is expanded).
Now I have declared the bottomsheet like this:
<LinearLayout
android:id="@+id/BSSECONDTOOLBAR"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="???"
app:layout_behavior="android.support.design.widget.BottomSheetBehavior"
android:layout_gravity="bottom"
android:gravity="bottom"
android:background="#f44242" />
Since this should be a direct child of a CoordinatorLayout
I cannot use the layout_weight
attribute.
My question is how do I set the BottomSheet
height in percentage?
There are two things to address in your question. The first is how to make the bottom sheet fill the parent when it is expanded.
This is quite simple: set android:layout_height="match_parent"
Then we have to address setting the peek height of the bottom sheet to be 20% of the parent. This is not possible to do in XML because CoordinatorLayout
doesn't support weights or percentages. Therefore, we have to set it in Java. You can add this code to your onCreate()
method:
// assume `coordinator` is your CoordinatorLayout
coordinator.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
@Override
public void onGlobalLayout() {
coordinator.getViewTreeObserver().removeOnGlobalLayoutListener(this);
int twentyPercent = (coordinator.getHeight() / 5);
// make the toolbar 20% of the screen
View toolbar = findViewById(R.id.your_toolbar_id);
ViewGroup.LayoutParams toolbarParams = toolbar.getLayoutParams();
toolbarParams.height = twentyPercent;
toolbar.setLayoutParams(toolbarParams);
// make the viewpager the rest of the screen (60%)
View pager = findViewById(R.id.your_viewpager_id);
ViewGroup.MarginLayoutParams pagerParams = (ViewGroup.MarginLayoutParams) pager.getLayoutParams();
pagerParams.topMargin = twentyPercent;
pagerParams.height = (coordinator.getHeight() - (twentyPercent * 2));
pager.setLayoutParams(pagerParams);
// make the bottomsheet 20% of the screen
View bottomSheet = findViewById(R.id.BSSECONDTOOLBAR);
BottomSheetBehavior<View> behavior = BottomSheetBehavior.from(bottomSheet);
behavior.setPeekHeight(twentyPercent);
}
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With