2011-03-11 108 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>