How to add image for button in android?
-
25-09-2019 - |
Question
How can I add an image to a button, rather than text?
Solution
Rather humorously, considering your tags, just use the ImageButton
widget.
OTHER TIPS
Simply use ImageButton View and set image for it:`
<ImageButton
android:id="@+id/searchImageButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_alignParentRight="true"
android:src="@android:drawable/ic_menu_search" />
As he stated, used the ImageButton
widget. Copy your image file within the Res/drawable/
directory of your project. While in XML simply go into the graphic representation (for simplicity) of your XML file and click on your ImageButton
widget that you added, go to its properties sheet and click on the [...] in the src:
field. Simply navigate to your image file. Also, make sure you're using a proper format; I tend to stick with .png files for my own reasons, but they work.
You should try something like this
<Button
android:id="@+id/imageButton1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="@drawable/qrcode"/>
the android:background="@drawable/qrcode"
will do it
<Button
android:id="@+id/button1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="News Feed"
android:icon="@drawable/newsfeed" />
newsfeed is image in the drawable folder
Put your Image in drawable folder. Here my image file name is left.png
<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_x="118dp"
android:layout_y="95dp"
android:background="@drawable/left"
android:onClick="toast"
android:text=" " />
You can create an ImageButton in your android activity_main.xml and which image you want to place in your button just paste that image in your drawable folder below is the sample code for your reference.
<ImageButton
android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_marginBottom="49dp"
android:layout_weight="1"
android:onClick="prev"
android:src="@drawable/prev"
/>
The new MaterialButton
from the Material Components can include an icon:
<com.google.android.material.button.MaterialButton
android:id="@+id/material_icon_button"
style="@style/Widget.MaterialComponents.Button.TextButton.Icon"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/icon_button_label_enabled"
app:icon="@drawable/icon_24px"/>
You can also customize some icon properties like iconSize
and iconGravity
.
Reference here.