如何以百分比设置协调器布局的孩子的高度?

Rad*_*hai 6 android android-coordinatorlayout bottom-sheet

我想设计一个由以下部分组成的布局:布局顶部的工具栏(应占屏幕的 20%),然后,垂直下方的 ViewPager(应占屏幕的 60%),然后仍然垂直下方,一个BottomSheet(折叠时应占屏幕的20%,展开时应占屏幕的100%)。
现在我已经像这样声明了底片:

<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" />
Run Code Online (Sandbox Code Playgroud)

由于这应该是 a 的直接子级,因此CoordinatorLayout我无法使用该layout_weight属性。

我的问题是如何BottomSheet以百分比设置高度?

Ben*_* P. 5

你的问题有两件事要解决。第一个是如何在展开时使底部工作表填充父级。

这很简单:设置 android:layout_height="match_parent"

然后我们必须解决将底部工作表的透视高度设置为父级的 20% 的问题。这在 XML 中是不可能的,因为CoordinatorLayout它不支持权重或百分比​​。因此,我们必须在 Java 中设置它。您可以将此代码添加到您的onCreate()方法中:

// 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);
    }
});
Run Code Online (Sandbox Code Playgroud)