按钮上文本的对齐方式

6
我正在创建一个自定义按钮。我想设置按钮上文本的位置。
  • 我有两个按钮背景图像(button_off和button_on),第一个是正常按钮,第二个是onFocus / onPressed状态。

enter image description here enter image description here

  • 现在我必须将文本放在按钮上,然后它应该看起来像:

enter image description here enter image description here

但是我无法在此背景按钮图像上设置文本的确切位置。 请分享您解决此问题的建议。


点击此链接 按钮,您将在此处得到答案。浏览此网站,您将学到很多。 - Prachur
2
我在链接的页面上找不到答案。此外,我认为将链接/文章集作为回答特定问题的方式是不好的风格。如果答案可以在文章中找到,至少直接链接到该文章。 - Hinton
6个回答

3
您可以在XML文件中设置这些属性,`
<Button
    android:id="@+id/button1"
    android:layout_width="120dp"
    android:layout_height="wrap_content"
    android:drawablePadding="5dp"
    android:drawableLeft="@android:drawable/ic_lock_lock"
    android:text="All" 
    android:gravity="center"/>

`


3

但是正如您在按钮图像中所看到的,文本并不在按钮的中心。它比中心多了5个像素。那么该怎么做呢? - Saurabh Pareek
当您将9-patch用作背景时,您需要手动(使用Google的“draw9patch”工具)定义可拉伸的区域以及文本出现的区域。我认为这应该可以解决您的问题。 - sergeytch

1

对齐文本,使用重力选项!或尝试使用填充。


我们只能在布局中使用填充,而不能用于文本。通过设置重力,我们只能设置左/右/上/下/居中对齐方式。但我想将文本设置为比中心点多5个像素。 - Saurabh Pareek
我甚至可以为文本使用填充! - sat

1
<Button
    android:id="@+id/button1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:drawableLeft="@android:drawable/arrow_down_float"
    android:background="@drawable/btn_all_bg"
    android:text="All">
 Button>

您可以使用drawableLeft / right / top / bottom在按钮上添加图标,文本会自动调整。


最好和简单的方法。感谢您的回答。 - Rohan Kandwal

0

您可以将布局用作按钮style="@android:style/Widget.Button",并根据需要进行配置。

将此粘贴到您的xml文件中:

<LinearLayout
android:id="@+id/button"
style="@android:style/Widget.Button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical" >
<TextView
    android:id="@+id/textView1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginLeft="2dp"
    android:text="TextView" />

</LinearLayout>

0

几种方法:

  1. 定义一个按钮并尝试使用 android:drawableStart
  2. 扩展 Button 并自己绘制
  3. 尝试定义一个包含文本和图像的 LinearLayout,并将其背景设置为您的按钮, 将它们两个的权重都设置为 1 并将它们放在另一个 LinearLayout 中,并使它们可以通过 onClick 被点击。 不能保证 3 可以正常工作,可能需要进行一些微调,但值得尝试。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接