【问题标题】:button text not getting centered vertically in button按钮文本没有在按钮中垂直居中
【发布时间】:2011-12-16 20:20:02
【问题描述】:

我正在创建一个 Android 应用程序,并且我有一个按钮,其背后有一个自定义背景图像。背景图像只是一个矩形,但现在按钮文本似乎没有垂直居中。这是我的按钮 xml:

<Button 
android:id="@+id/save_to_list"
android:layout_below="@+id/info_pic"
android:text="SAVE TO LIST"
android:textColor="@android:color/white"
android:layout_centerHorizontal="true"
android:layout_gravity="center_horizontal"
android:layout_width="260dp"
android:layout_height="35dp"
android:layout_marginTop="15dp"
android:layout_marginBottom="15dp"></Button>

我在这里设置背景:

ImageView button_bg = (ImageView)findViewById(R.id.button_background);
savetolist_button.setBackgroundDrawable(button_bg.getDrawable());

是否可以在哪里更改按钮内文本的位置?

【问题讨论】:

    标签: android xml button


    【解决方案1】:

    android:layout_gravity 定义其父级内的布局对齐方式。要在按钮内对齐文本,您需要 android:gravity,例如

    <Button 
        ...
        android:gravity="center"
        ...>
    </Button>
    

    【讨论】:

    • 另外,可以添加includeFontPadding = false 来移除字体特定的填充
    【解决方案2】:

    您的按钮太短,无法正确容纳文本。增加layout_height,文字应该居中。

    【讨论】:

      【解决方案3】:

      您的文本可能在每个字母的字体中内置了一些填充,这就是您的文本被推向一个方向的原因。将 layout_height 设置为“wrap_content”,您的文本现在应该正确居中。

      【讨论】:

        【解决方案4】:

        我发现最好将 9 个补丁图像用于矩形背景而不是 xml 可绘制对象。

        【讨论】:

          猜你喜欢
          • 2013-06-04
          • 2012-01-05
          • 2021-10-06
          • 2023-03-05
          • 2013-07-31
          • 2020-02-16
          • 2016-12-23
          • 1970-01-01
          • 2017-02-05
          相关资源
          最近更新 更多