首页 > 解决方案 > 如何忽略子元素的边距?

问题描述

背景

我正在通过将操作系统生成的通知视图注入我自己的布局来开发自定义通知布局。我的布局必须尽可能短,这是50dp在 Android 10 中。

问题

我注入到视图中的视图有边距,导致它把我的布局50dp66dp.

代码

以下布局简化了演示问题的过程:

<?xml version="1.0" encoding="utf-8"?>

<FrameLayout
    android:id="@+id/activity_layout"
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <LinearLayout
        android:id="@+id/container"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:minHeight="50dp"
        android:orientation="horizontal"
        >

        <TextView
            android:id="@+id/full_height_view"
            android:layout_width="10dp"
            android:layout_height="match_parent"
            android:background="@android:color/holo_blue_bright"
            />

        <TextView
            android:id="@+id/bad_view"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginTop="46dp"
            android:layout_marginBottom="20dp"
            android:background="@android:color/holo_red_light"
            >
        </TextView>

    </LinearLayout>
</FrameLayout>

请注意,我不想超过 50dp containerminHeight问题是从bad_view总和到 66dp 的边距并将父级拉伸到 66dp。

问题

如何防止上边距bad_view将父级拉伸超出其最小高度?我无法在父级上设置固定高度,因为确切的高度取决于操作系统。而且我无法修改bad_view,因为它是由操作系统生成的。

标签: androidandroid-layout

解决方案


我找到了另一个解决方案:使用GridLayout垂直权重来覆盖有问题的视图的高度。这给了我加权水平的灵活性,LinearLayout但增加了垂直重量。


推荐阅读