Wednesday, 14 June 2017

How to Use Image as a Button in Android

How-to-Use-Image-as-Button-in-Android


Download Source Code


Still now we have learned to work with buttons, now we will learn to use images as buttons , as we see now a days in our mobiles.

Its just copy pasting a image in a drawable folder which is under the res folder and adding it in the  activity_main.xml file.


we used color code inside the android:background="#EAAC00"  instead of the color code we are typing the location of the image ex: android:background= "@drawable/imagename" .


Let us see in detail.

Create a New Android Application Project, and drag and drop a Button in the  layout.

How-to-Use-Image-as-Button-in-Android

Now create a New Folder in the res folder named as drawable. 

drawable-folder

Right click on the res folder and click New---> Folder and name the folder as drawable and click Finish.

new-drawable-folder

drawable-folder


Now the created drawable folder can be seen below the res folder.

drawable-folder

Now copy any image that you want use as button and paste in the drawable folder.

Copy image from your computer

copy-image

and right click on the drwable folder and paste it.

paste-image-in-drawable-folder

Now you can see that the image has been pasted inside the drawable folder.

image-in-drawable-folder

Now open activity_main.xml file and delete the  android:text="Button" since we do not need any text for our image.

activity-main-xml

then add the following code    android:background="@drawable/music"  as in the image

How-to-Use-Image-as-Button-in-Android-code

Then save it and open the Graphics Layout .

Image-as-Button-in-Android

Now the button is changed into an image, but it is too big, we can resize it by using the width and height property in the activity_main.xml file.

I am using 100 dp for both width and height.

width-height-property-in-android

save it and open Graphics layout

resized-image

Now we can see the resized image button.

Now we want make some action for that button, we can simply use a Toast message for that.

Open MainActivity.java and register the button , implement the listener interface and add the unimplemented methods as we saw in the post How to use Buttons in Android .

button-code


Then write the Toast message code

Toast-message-code-in-android

Now save and run the program.

Read 

How to use Android Phone as an Emulator




Use-Image-as-Button-in-Android

Use-Image-as-Button-in-Android

You can try with multiple buttons using images as we saw in the post
Working with Multiple Buttons in Android  


You can try the combinations of these example and make your own example.

 Also Read:

How to change Background Color in Android

No comments :

Post a Comment