为什么drawableStart的行为与Android文档不匹配?

Nat*_*man 8 android button spacing drawable

我创建了一个非常基本的布局:

<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>
Run Code Online (Sandbox Code Playgroud)

根据文件drawableStart,

"可以在文本开头绘制的可绘制内容."

但是,当我在Android 4.0.4手机上运行时,我会看到:

在此输入图像描述

为什么图标和文字之间有这么大的差距?根据这个答案,

"使用Android 4.0(API级别14),您可以使用android:drawableStart属性在文本的开头放置一个drawable."

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

A. *_*and 6

开始和结束都有很多误解.布局xml中的
开始结束右的替代,以匹配布局方向(LTR或RTL).

所以,当文件说:

"可以在文本开头绘制的可绘制内容."

你必须阅读:

"根据布局方向绘制到视图开头的drawable"


小智 0

原因是因为 drawableStart 使按钮变成复合布局,即图像视图和 TextView 全部包裹在“按钮”中......

所以你看到的是 ImageView 被放置在 Textview 的前面。但是 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>
Run Code Online (Sandbox Code Playgroud)

  • 但这并不使文本和图标居中。 (4认同)