Reputation: 5594
I wanted to make two equally-sized radio buttons with a custom background, text, and an image to the right of the text. Because of how different these are from a standard "Button", I made them using a clickable "RelativeLayout".
The text and the image are of different heights, but I want each one to be centered vertically in the button. I also want the combination of the text+image to be centered horizontally in the button. This second part is what I'm having trouble with; it's off-center, close to the left side. In the image below, the left side is what I want, but the right side is what's happening. The image on one of the buttons (the one with the longer text) is resized to be smaller, too... Though there is still plenty of space on the right side of the button.
Here is my code:
<LinearLayout
android:baselineAligned="false"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<RelativeLayout
android:id="@+id/my_button"
android:background="@drawable/radio_button"
android:layout_weight="1"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:gravity="center_horizontal">
<TextView
android:id="@+id/button_textview"
android:text="@string/button_label"
android:textAppearance="?android:attr/textAppearanceButton"
android:layout_centerVertical="true"
android:layout_width="wrap_content"
android:layout_height="wrap_content"></TextView>
<ImageView
android:contentDescription="@string/image_description"
android:id="@+id/button_imageview"
android:layout_centerVertical="true"
android:src="@drawable/my_icon"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toRightOf="@id/button_textview">
</ImageView>
</RelativeLayout>
<RelativeLayout
... same thing for the second button ...
</RelativeLayout>
</LinearLayout>
What am I doing wrong?
Upvotes: 1
Views: 1071
Reputation: 5594
Turns out the solution was adding
android:paddingRight="0dip"
strangely enough, even though I didn't put any padding there in the first place.
Upvotes: 0
Reputation: 29436
Use this as your button:
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:layout_gravity="center_horizontal"
>
<TextView android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical"
android:text="MyButton"/>
<ImageView android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical"
android:src="@drawable/my_image"/>
</LinearLayout>
Now, you can place it in other parent views. To apply layout attributes to above button, place those attributes in the outer <LinearLayout>
tag of above button.
Alternative:
You can set custom images to be drawn on sides(Left,Right,Top,Bottom) of a TextView
using attributes like:
android:drawableLeft="@drawable/my_image"
Upvotes: 1