如何在Coordinator Layout的子视图中设置高度百分比?

6

我希望设计一个布局,包括:在布局顶部占据20%屏幕宽度的工具栏,然后在垂直方向下方是一个ViewPager(占据60%屏幕宽度),再在垂直方向下面是一个BottomSheet(在折叠时占据屏幕的20%,在展开时占据100%屏幕宽度)。


现在我已经像这样声明了bottomsheet:

<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" />

由于该视图应为CoordinatorLayout的直接子级,因此无法使用layout_weight属性。

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

2个回答

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);
    }
});

首先,很抱歉回复晚了。其次,我正在使用C#和Xamarin,但没有问题。所以,根据你的说法,我的布局草图应该是这样的: <Toolbar><ViewPager> 放在 <LinearLayout> 中,因此我可以使用 layout_weight 属性来设置它们的百分比。在我按照这种方式声明布局文件之后,我应该使用你的代码使 BottomSheet 占据屏幕的 20%,对吗? - Raducu Mihai
我认为只需要<CoordinatorLayout><Toolbar/><ViewPager/><BottomSheet/></CoordinatorLayout>,不需要在任何地方使用LinearLayout。 - Ben P.
好的,但是如果我不使用LinearLayout作为Toolbar和ViewPager的父级,我该如何将它们的高度设置为屏幕的20%和60%? - Raducu Mihai
@RaducuMihai 看看我的更新答案。手动定位视图有点烦人,但是 CoordinatorLayout 并不支持这些功能,所以你必须自己完成。 - Ben P.
我明白了。为了完成这个任务,我尝试了很多次,我想我已经尝试过使用你的方法来做了,也许我做错了什么。我会尝试你的代码并告诉你它是否有效。非常感谢你。 - Raducu Mihai

1
我知道这可能有些晚了,但这个答案可能会对某些人有所帮助...
我通过以下代码实现了半屏布局。
BottomSheetBehavior.from(bottom_sheet).peekHeight =
        (Resources.getSystem().getDisplayMetrics().heightPixels)/2

我希望覆盖任何尺寸设备的一半屏幕,因此我通过除以2来实现。通过更改分隔符,您可以使用上述代码覆盖所需的设备屏幕大小。将此代码放置在底部工作表弹出的活动中。(在onCreate方法中)在代码中,bottom_sheet是赋予底部工作表根布局的ID。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接