问题
I have created a very basic layout:
<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>
According to the documentation for drawableStart,
"The drawable to be drawn to the start of the text."
However, when run on my Android 4.0.4 phone, I instead see this:
Why is there such a large gap between the icon and the text? According to this answer,
"With Android 4.0 (API level 14) you can use android:drawableStart attribute to place a drawable at the start of the text."
But this is not the behavior I observe. Why isn't the attribute working?
回答1:
A lot of misunderstanding with start and end.
Start and End in layout xml are alternative to left and right to match layout direction (LTR or RTL).
So, when documentation says :
"The drawable to be drawn to the start of the text."
You must read :
"The drawable to be drawn to the beginning of the view according to layout direction"
回答2:
The reason is because drawableStart kind of makes the button into a compound layout i.e Image view and TextView all wrapped in a 'Button'...
So what you are seeing is that the ImageView is placed in front of the Textview.. However the TextView still has its default layout attributes set so that it draws it centered in the space left for it hence the gap (notice its centered in the space left by putting the Image at the beginning of the text)
so you basically need to override the gravity attribute for the buttons TextView -
android:gravity="center_vertical|center_horizontal|left"
see below notice that you only need to have the button wrapped by 1 layout the other is redundant... i.e The RelativeLayout could be a LinearLayout on its own too since you only have one view in the layout!
<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>
来源:https://stackoverflow.com/questions/15350990/how-come-the-behavior-of-drawablestart-doesnt-match-the-android-documentation