2011-03-11 107 views
6

我正在创建自定义按钮。我想设置按钮上文字的位置。按钮上的文本对齐方式

  • 我有两个背景图像的按钮(button_off和button_on)第一个是正常的按钮,第二个是onFocus/onPressed状态。

enter image description here enter image description here

  • 现在我已经把按钮文字那么就应该是这样的:

enter image description here enter image description here

,但我无法设定确切该背景按钮图像上文本的位置。 请分享你的建议来解决这个问题。

+0

请点击此链接[按钮](http://www.androidpeople.com/button),U将得到答案在这里。并通过这个网站冲浪你会学到很多 – Prachur

+0

感谢它有用的链接。 –

+2

我无法在链接页面上找到答案。此外,我认为发布链接/文章集合作为特定问题的答案是一种糟糕的风格。如果可以在文章中找到答案,至少可以直接链接到文章。 – Hinton

回答

3

您可以尝试使用9补丁图像作为背景。有关此处的更多信息:http://developer.android.com/guide/topics/graphics/2d-graphics.html#nine-patch

+0

我第二。 9贴片是首先想到的。 – trgraglia

+0

但正如您在该按钮中看到的那样,图像文本不在按钮的中心。那就是中心以上5个像素。那么该怎么做? –

+0

当您使用9-patch作为背景时,您可以手动(使用Google的“draw9patch”工具)定义可拉伸的区域以及文本将出现的区域。我认为它应该可以解决你的问题。 – sergeytch

1

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

+0

我们可以使用填充只用于布局而不是文本。通过设置重力,我们只能设置左/右/上/下/中心对齐。但我想设置文本5像素多中心.. –

+0

我甚至能够使用填充文本! – sat

0

几个方面:

  1. 定义按钮,并尝试android:drawableStart
  2. 扩展按钮,绘制自己
  3. 试图定义一个LinearLayout持有文本和图像与 背景 设置它们两个的权重为1,并将它们放入另一个LinearLayout并使它们成为onClick 无法保证3将不经过调整或两次工作,但它值得尝试
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 /右/上/下到上的按钮添加图标和文本会自动调整。

+0

最好,最简单的方法。感谢你的回答 –

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"/> 

`

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>