Android RelativeLayout 中的按钮未填满 space

Android Button not filling full space in RelativeLayout

我正在尝试创建一个与页面底部对齐的按钮。我希望它从左、右和底部填充 100% space。无论我选择什么属性,仍然有非常小的未覆盖区域。你能帮忙吗?

    <?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="fill_parent"
    android:layout_height="match_parent"
    tools:context="com.example.myapplication.MainActivity">

    <Button
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:layout_alignParentLeft="true"
        android:layout_alignParentRight="true"
        android:layout_margin="0dp"
        android:padding="0dp"
        android:text="search"

        />
</RelativeLayout>

Here is the screenshot, showing not filled areas

您看到的 space 是其背景可绘制对象中按钮周围的阴影。您需要创建自己的可绘制背景,然后它应该完全占据宽度。

或者,您也可以将背景设置为空。

android:background="@null"

像这样在 drawable 文件夹中创建一个文件,比如 simple_selector.xml

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">

    <item android:state_pressed="false">
        <shape android:shape="rectangle">
            <!-- Normal color -->
            <solid android:color="@android:color/white" />
        </shape>
    </item>

    <item android:state_pressed="true">
        <shape android:shape="rectangle">
            <!-- Color - when the view is pressed -->
            <solid android:color="@android:color/black"/>
        </shape>
    </item>
</selector>

现在只需将背景设置为上面创建的 drawable。

<Button
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:layout_alignParentLeft="true"
        android:layout_alignParentRight="true"
        android:background="@drawable/simple_selector"
        android:text="search"

        />

以上代码可以在按钮的 normalpressed 状态下改变颜色。您可以根据需要更改颜色。