【问题标题】:Vertical LinearLayout with weights & marginTop -ve具有权重和边距的垂直线性布局Top -ve
【发布时间】:2018-03-03 14:54:33
【问题描述】:

我想创建一个类似这样的屏幕,但底部没有空白(如果看不到空白请点击图片)

红色部分应占高度的 40%。黑色布局剩余 (60% + (-24dp marginTop) )。

另外,我有两个不同的要求:

  1. 这个确切的屏幕(已由 ADM 回答)
  2. 整个屏幕应该是可滚动的(在 NestedScrollView 内)(需要解决方案)

以下是我的 XML:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:weightSum="100">

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="0dip"
    android:layout_weight="40"
    android:background="#f00"
    android:orientation="vertical" />

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="0dip"
    android:layout_marginEnd="12dp"
    android:layout_marginStart="12dp"
    android:layout_marginTop="-24dp"
    android:layout_weight="60"
    android:background="@android:color/black"
    android:orientation="vertical" />

</LinearLayout>

我知道这可以通过给定一个固定高度来解决,但我不想这样做。

【问题讨论】:

    标签: android android-layout android-linearlayout


    【解决方案1】:

    解决方案可以是多个,也许使用FrameLayoutConstraitLayout 会很容易。下面是结合RelativeLayoutLinearLayout的解决方案。

    <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
    
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical"
        android:weightSum="10">
    
        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="0dip"
            android:layout_weight="4"
            android:background="#f00"
            android:orientation="vertical" />
    
    </LinearLayout>
    
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical"
        android:weightSum="10">
    
        <android.support.v4.widget.Space
            android:layout_width="match_parent"
            android:layout_height="0dp"
            android:layout_weight="3.8" />
    
        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="0dip"
            android:layout_marginLeft="20dp"
            android:layout_marginRight="20dp"
            android:layout_weight="6.2"
            android:background="#000000"
            android:orientation="vertical" />
    
    
    </LinearLayout>
    

    【讨论】:

    • 您的回答很好。如果整个页面都是 NestedScrollView,你能告诉我如何使同样的情况起作用吗?
    • 您在问题中说黑色部分将是滚动视图。所以只需将滚动视图代替线性布局。
    • 如果整个页面是嵌套滚动视图,我认为它的行为与线性布局一样,因为你已经划分了权重。
    • 如果此答案对您有所帮助,请接受并投票。谢谢