【问题标题】:Button and background margin shifted按钮和背景边距移动
【发布时间】:2023-03-17 00:32:01
【问题描述】:

我正在使用 android studio,我尝试使用一些按钮在 UI 上做一些工作。

我为一些按钮创建了背景,但是当我在按钮上应用此背景时,按钮内的文本没有居中。

我认为按钮的边距保持不变,而应用的背景创建的正方形比按钮的边距更小。我不知道如何使按钮的边距适合背景xml文件中编码的正方形的边距。

这里是问题的图片:

pic1

这里是后台的代码(bg_rectangle_grey.xml):

<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:width="@dimen/_34sdp" android:height="@dimen/_34sdp">
        <shape android:shape="rectangle">
            <stroke android:width="1dp" android:color="#ff6c7780" />
            <corners android:radius="3dp" />
        </shape>
    </item>
</layer-list>

这里是带有按钮的 xml 文件的代码:

  <LinearLayout
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:orientation="horizontal"
            android:layout_marginTop="@dimen/_15sdp"
            android:style="?android:attr/buttonBarStyle">

            <Button
                android:style="?android:attr/buttonBarButtonStyle"
                android:background="@drawable/bg_rectangle_grey"
                android:id="@+id/button4"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_weight="1"
                android:text="M" />

我已经在谷歌上寻找答案,但它从来都不是我想要的。

如果有人可以提供帮助。 提前谢谢你

【问题讨论】:

  • 你显示 buttonBarButtonStyle 和 buttonBarButtonStyle 代码。
  • 你可以为这个布局发布完整的 xml

标签: android xml button background


【解决方案1】:

只需在按钮中使用重力center

       <Button
            android:style="?android:attr/buttonBarButtonStyle"
            android:background="@drawable/bg_rectangle_grey"
            android:id="@+id/button4"
            android:gravity="center"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="M" />

【讨论】:

  • 感谢您的回答。但是我已经尝试过重力和 layout_gravity。它没有工作
【解决方案2】:

请从下面的代码中删除 android:width="@dimen/_34sdp" android:height="@dimen/_34sdp" 并重试。

<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:width="@dimen/_34sdp" android:height="@dimen/_34sdp">
        <shape android:shape="rectangle">
            <stroke android:width="1dp" android:color="#ff6c7780" />
            <corners android:radius="3dp" />
        </shape>
    </item>
</layer-list>

【讨论】: