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

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

问题描述:

我有按钮定义如下:如何在Android中的Button上垂直居中drawableTop和文本?

<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”对齐图像按钮视图的顶部的边界。我想将它(与文本标签一起)垂直放置在按钮上。

'android:gravity'似乎只对文本标签有效。它不会影响'drawableTop'的位置。

我能够垂直居中使用'android:paddingTop' - 但这似乎不是一个好主意。我想它不能在不同的屏幕分辨率/尺寸下正常工作。

+0

drawableTop,就像其名称所暗示的那样,始终将drawable对齐到Button的顶部。尝试drawableLeft来代替,或者如果你希望它在文本背后,android:background。 – 2010-04-15 16:12:05

新的答案

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

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

...,随函附上的ImageViewTextView内。


老答案

这里有一个想法:包裹在一个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"?看起来不正确。而不是背景

+0

这几乎是工作。但效果有点不同 - 现在我的标签放在我的图标上。我想将它放在图标的下方,但两者都集中在按钮上。 – grzaks 2010-04-15 12:11:13

+0

LinearLayout样式的解决方案效果很好。 – grzaks 2010-04-15 12:59:47

+0

@Felix,使用'android:layout_weight'时使用'android:layout_width =“0dp”'。这告诉Android使用权重根据封闭布局中有多少可用空间来计算大小。 – karl 2013-02-12 21:51:20

'android:gravity'似乎只能在文本标签上使用 。它不会影响 'drawableTop'的定位。

正确。

我能够使用“机器人:paddingTop”垂直 居中 - 但 似乎不是一个好主意。我 猜测它不会正常工作在 不同的屏幕分辨率/大小。

您可能可以通过使用维度资源解决此问题。

但是,除了通过填充以外,不能“在Button上居中绘制垂直顶部和文本”。 Button的可绘制特征不是非常可配置的。

+0

好的,我会尝试填充。谢谢 – grzaks 2010-04-15 11:44:53

+0

因此,SO真的需要一个功能来+1正确的答案,但-1它不喜欢的答案。 – Justin 2014-10-03 18:12:36

+0

在按钮布局中使用android:paddingTop可以使我垂直居中绘制顶部。 +1为正确的答案。 – 2015-02-23 16:11:34

使用android:drawableTop="@drawable/Icon"不要忘记更改

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

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

我确定它。

您可以使用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>