如何在Android中使Button上的drawableTop和文本垂直居中?

15

我定义了一个按钮如下:

<Button
 android:drawableTop="@drawable/ico"
 android:gravity="center"
 android:id="@+id/StartButton2x2"
 android:text="@string/Widget2x2StartBtnLabel"
 android:layout_width="0dip" 
 android:layout_height="fill_parent"
 android:layout_weight="1" 
 android:background="@drawable/widgetbtn_bg"
/>

问题在于'drawableTop'图像与Button视图的顶部边框对齐。我希望能将它(以及文本标签)垂直居中在按钮上。

'android:gravity'似乎只对文本标签起作用。它不影响'drawableTop'的位置。

我能够使用'android:paddingTop'来垂直居中它 - 但是这似乎不是一个好主意。我猜它在不同的屏幕分辨率/大小上可能无法正常工作。


drawableTop,顾名思义,始终将Drawable对齐到按钮的顶部。尝试使用drawableLeft代替,或者如果您想要它在文本后面,则使用android:background。 - Romain Guy
5个回答

13

新的回答

显然我误解了问题。答案是使用:

<LinearLayout
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical"
    style="@android:style/Widget.Button">

在其中嵌套一个ImageView和一个TextView,可以尝试使用FrameLayout进行布局。


旧版回答

建议:将您的按钮放在一个FrameLayout中。例如:

<FrameLayout
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:foreground="@drawable/ico"
    android:foregroundGravity="center">
    <Button
        android:gravity="center_vertical"
        android:id="@+id/StartButton2x2"
        android:text="@string/Widget2x2StartBtnLabel"
        android:layout_width="0dip"
        android:layout_height="fill_parent"
        android:layout_weight="1" 
        android:background="@drawable/widgetbtn_bg" />
</FrameLayout>

顺便问一下,android:layout_width="0dip"是怎么回事?看起来不对啊。


这几乎可以工作。但效果有点不同 - 现在我的标签在图标上方。我想要它在图标下方,但两者一起居中在按钮上。 - grzaks
@FelixпәЊеҢ“дҢүз”Ёandroid:layout_weightж—¶пәЊж‚ЁеЏҮд»ӨдҢүз”Ёandroid:layout_width="0dp"гЂ‚иү™дәље‘ЉиҮ‰Androidж №жҚ®еЊ…еђ«еёѓе±Ђдё­еЏҮз”Ёзљ„з©ғй—өжқӨи®Ұ算大小。 - karl

9
'android:gravity' 似乎只对文本标签起作用,不影响 'drawableTop' 的定位。
正确。
我能够使用 'android:paddingTop' 在垂直方向上将其居中 - 但这似乎不是一个好主意。我猜在不同的屏幕分辨率/大小上它不会正常工作。
您可以尝试使用尺寸资源来解决这个问题。
然而,除了通过填充之外,您无法 "在按钮上垂直居中drawableTop和文本"。 Button的可绘制功能不是非常可配置的。

Stack Overflow真的需要一个功能,可以为正确的答案点赞+1,但是也可以因为不喜欢答案而踩它-1。 - Justin
在按钮布局中使用android:paddingTop对我来说起到了垂直居中drawableTop的作用。正确答案加1。 - Andre Rocha

0

你可以使用TextView及其属性。

<LinearLayout
            style="@android:style/Widget.Button"
            android:layout_width="fill_parent"
            android:layout_height="fill_parent"
            android:orientation="vertical" >

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:drawableLeft="@drawable/.."
                android:text="" />
        </LinearLayout>

-1
<Button
  android:id="@+id/....."
  android:...............
  .......................
  android:gravity="center_horizontal"
/>

我对此感到满意。


-2

使用 android:drawableTop="@drawable/Icon" 代替背景

别忘了更改

android:layout_width="fill_parent"
android:layout_height="wrap_content"

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