2013-03-12 40 views
8

我创建了一个非常基本的布局:drawableStart的行为如何与Android文档不匹配?

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    xmlns:tools="http://schemas.android.com/tools" 
    android:layout_width="match_parent" 
    android:layout_height="match_parent" > 

    <LinearLayout 
     android:layout_width="match_parent" 
     android:layout_height="wrap_content" > 

     <Button 
      android:id="@+id/button1" 
      android:layout_width="match_parent" 
      android:layout_height="wrap_content" 
      android:text="Button" 
      android:drawableStart="@drawable/ic_launcher" /> 

    </LinearLayout> 
</RelativeLayout> 

the documentation for drawableStart

“的绘制被吸引到该文本的开始。”

但是,当我的Android 4.0.4的手机上运行,​​而不是我看到这一点:

enter image description here

为什么会出现图标和文本之间如此大的差距?据this answer

“有了Android 4.0(API级别14)可以使用Android:drawableStart属性放置绘制的文本的开始”

但这不是我观察到的行为。为什么这个属性不起作用?

+0

文档说这是在API 17 – speedynomads 2015-01-07 17:51:25

回答

1

的原因是因为drawableStart一种使按钮成复合布局,即图像视图和TextView的所有包裹在一个“按钮” ...

所以你看到的是,ImageView的放在前面。但是,TextView仍然具有其默认布局属性设置,因此它将它绘制在为它留下的空间中居中,因此它的间隙(注意它将图像放在文本的开头处留下的空间的中心)

所以你基本上需要重写按钮的重力属性TextView -

android:gravity="center_vertical|center_horizontal|left"

见下文通知,您只需要拥有由1个布局包裹按钮,另一个是多余的... 即该RelativeLayout的可能是自身的一个的LinearLayout过,因为你只有在布局一个视图!

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    android:layout_width="match_parent" 
    android:layout_height="match_parent" > 

    <Button 
     android:id="@+id/button1" 
     android:layout_width="match_parent" 
     android:layout_height="wrap_content" 
     android:drawableStart="@drawable/ic_launcher" 
     android:gravity="center_vertical|center_horizontal|left" 
     android:text="@string/app_name" /> 

</RelativeLayout> 
+2

这增加的绘制被吸引到该视图的开始尽管如此,文本和图标并不居中。 – ZaBlanc 2016-05-10 19:10:34

6

很多误区与开始和结束。
在布局XML开始结束是替代匹配布局方向(LTR或RTL)。

所以,当文档中说:

“的绘制被吸引到文本的开始。“

您必须阅读:

‘根据布局方向’