How to set height for Coordinator Layout's childs 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);
}
});