默认添加线性布局边距。如何避免这种情况? Android

Linear Layout margin added by default. How to avoid that? Android

我在线性布局中创建了 4 个按钮。这是我的xml。

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


<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal"
    android:weightSum="3">
    <Button android:id="@+id/button1"
        android:layout_weight="1"
        android:layout_height="match_parent"
        android:layout_width="wrap_content"
        android:text="Account"
        />
    <Button android:id="@+id/button2"
        android:layout_weight="1"
        android:layout_height="match_parent"
        android:layout_width="wrap_content"
        android:text="History"
        />
    <Button
        android:id="@+id/button3"
        android:layout_weight="1"
        android:layout_height="match_parent"
        android:layout_width="wrap_content"
        android:text="Settings"
        />
</LinearLayout>

但在布局上方为所有 3 个按钮添加边距。为什么默认添加边距?如何避免这种情况?

在按钮中,设置 android:layout_width="0dp" 而不是 wrap_content

这是因为你给水平LinearLayout的按钮赋予了weight属性,每个Button将水平填充根布局的1/3。 如果您使用的是垂直 Linear Layout,则应设置 android:layout_height="0dp"

希望对您有所帮助。

试试这个,它会如你所愿,

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

    <Button android:id="@+id/button1"
        android:layout_weight="1"
        android:layout_height="match_parent"
        android:layout_width="match_parent"
        android:text="Account"
        android:background="#80ffdd10"
        />
    <Button android:id="@+id/button2"
        android:layout_weight="1"
        android:layout_height="match_parent"
        android:layout_width="match_parent"
        android:background="#800aad10"
        android:text="History"
        />
    <Button
        android:id="@+id/button3"
        android:layout_weight="1"
        android:layout_height="match_parent"
        android:layout_width="match_parent"
        android:text="Settings"
        android:background="#8c9eff"
        />
</LinearLayout>

这些是 Android Button Widget 默认的阴影。但是,如果您想将一个按钮与另一个按钮强行连接,请根据需要将以下属性添加到每个 buttons

android:layout_marginRight="-5dp"
android:layout_marginLeft="-5dp"

注意:根据需要增加或减少属性的值(当前为-5dp)。

您可以使用自定义背景,它会解决您的问题

android:background="#8c9eff"