Wednesday, 14 June 2017
How to Use Image as a 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.
In the post Changing color of a button
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.
Now create a New Folder in the res folder named as drawable.
Right click on the res folder and click New---> Folder and name the folder as drawable and click Finish.
Now the created drawable folder can be seen below the res folder.
Now copy any image that you want use as button and paste in the drawable folder.
Copy image from your computer
and right click on the drwable folder and paste it.
Now you can see that the image has been pasted inside the drawable folder.
Now open activity_main.xml file and delete the android:text="Button" since we do not need any text for our image.
then add the following code android:background="@drawable/music" as in the image
Then save it and open the Graphics Layout .
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.
save it and open Graphics layout
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 .
Then write the Toast message code
Now save and run the program.
Read
How to use Android Phone as an Emulator
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
Subscribe to:
Post Comments
(
Atom
)
No comments :
Post a Comment