Button with text AND an image (Android)
I want to create an android button with both an image and text, but the text is automatically centered. How do I place the text at the bottom of the button?
I know I can use relative layout 开发者_Python百科to place a second text button underneath the image, but I prefer to minimize the code.
You can declare where on the button you want to assign the image (Im assuming you already have the image on the button):
<Button
android:id="@+id/button"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="- I'm a Button -"
android:drawableTop="@drawable/icon"
/>
you can also set padding between the text and image with android:drawablePadding(int)
The drawableTop attribute can be changed to drawableRight, Left, Bottom, etc. good luck!
You can also do like this
<LinearLayout
android:id="@+id/image_button_2"
style="@android:style/Widget.Button"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="15dp"
android:gravity="center">
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginRight="5dp"
android:src="@drawable/ic_gear" />
<TextView
android:id="@+id/image_button_2_text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="@android:color/black"
android:text="Button 2" />
</LinearLayout>
In your activity
final View button2 = findViewById(R.id.image_button_2);
button2.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
If I were you I would just not use a Button. Use LinearLayout, or RelativeLayout and just give it the Button background(Hint: use a selector if you want it to have different images for each state) and place your TextView inside of it, then you can use the drawableLeft, drawableTop etc.. attributes to put the picture on whichever side you want. If you want a greater level of control as to where the picture goes in relation to the text then use one TextView and one ImageView. Then in your java just get a reference to your layout and treat it just like you would a button, with setOnClickListener().
You can try something like this
<Button
android:id="@+id/ButtonTest"
android:text="this is text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="@drawable/icon"
**android:gravity="bottom"**/>
I think the simplest way to achieve this (with pure XML) is:
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:onClick="onClickMethod"
android:orientation="vertical"
android:clickable="true">
<ImageView
android:src="@drawable/YOUR_DRAWABLE"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:clickable="false"/>
<TextView
android:text="@string/YOUR_TEXT"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:clickable="false"/>
</LinearLayout>
精彩评论