【问题标题】:How come the behavior of drawableStart doesn't match the Android documentation?为什么 drawableStart 的行为与 Android 文档不匹配?
【发布时间】:2013-02-27 08:40:57
【问题描述】:

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

<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

“要绘制到文本开头的drawable。”

但是,在我的 Android 4.0.4 手机上运行时,我却看到了这个:

为什么图标和文字之间的差距这么大?根据this answer

“使用 Android 4.0(API 级别 14),您可以使用 android:drawableStart 属性在文本开头放置一个可绘制对象。”

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

【问题讨论】:

  • 文档说这是在 api 17 中添加的

标签: android button drawable spacing


【解决方案1】:

对 start 和 end 有很多误解。
StartEnd 在布局 xml 中可以替代 left以匹配布局方向(LTR 或 RTL)。

所以,当文档说:

“要绘制到文本开头的drawable。”

你必须阅读:

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

【讨论】:

    【解决方案2】:

    原因是因为 drawableStart 使按钮成为复合布局,即 Image view 和 TextView 都包裹在一个 'Button' 中......

    所以你看到的是 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>
    

    【讨论】:

    • 不过,这不会使文本和图标居中。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2010-10-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-06-28
    • 2013-02-03
    相关资源
    最近更新 更多