线性布局中的权重分布视图之间居中上方的视图

view centered above in between weight distributed views in linear layout

我正在尝试实现如下布局:

线性布局中权重为 2(绿色视图)和 1(蓝色视图)的两个视图。一个浮动按钮位于它们前面的视图之间。但是使用线性布局是不可能的。任何人都可以在这里提供一点帮助

更新: 这是我所做的

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <View
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="2"
        android:background="#22B14C" />

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal"
        android:text="To be a floating button" />

    <View
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1"
        android:background="#00A2E8" />
</LinearLayout>

而我得到的是

如果您想按照自己的方式使用 LinearLayout,唯一可以做到这一点的方法是为按钮定义固定高度。然后你可以像这样实现覆盖

<Button
    android:layout_width="wrap_content"
    android:layout_height="48dp"
    android:layout_marginTop="-24dp"
    android:layout_marginBottom="-24dp"
    android:layout_gravity="center_horizontal"
    android:text="To be a floating button"/>

但是由于使用布局权重不是一个好的做法,我建议切换到 RelativeLayout

多亏了CoordinatorLayout in the Design Support Library这个问题才得以解决。

<android.support.design.widget.CoordinatorLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical">

        <View
            android:id="@+id/top"
            android:layout_width="match_parent"
            android:layout_height="0dp"
            android:layout_weight="2"
            android:background="#22B14C" />

        <View
            android:id="@+id/bottom"
            android:layout_width="match_parent"
            android:layout_height="0dp"
            android:layout_weight="1"
            android:background="#00A2E8" />
    </LinearLayout>

    <android.support.design.widget.FloatingActionButton
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_margin="@dimen/fab_margin"
        app:backgroundTint="#a349a4"
        app:fabSize="normal"
        app:layout_anchor="@id/top"
        app:layout_anchorGravity="bottom|right|end" />

</android.support.design.widget.CoordinatorLayout>

您必须使用 layout_anchor 属性将 FloatingActionButton 锚定到顶视图,然后使用 layout_anchorGravity

设置锚引力

这是你得到的: