Welcome. In this tutorial you will learn about Image Button in Android Studio.
Image Button Example for Android Studio
An Image Button is a type of Button used in Android Studio which displays an Image in place of the regular button UI. That image is clickable and works exactly like a button, only difference being the UI and the text being displayed on the button. You can even customize it like a button that changes background colours during different background states. There are two ways to set the image:-
1. By using the android:src attribute in XML file.
2. By using the ImageView.setImageResource() method.
Inserting the Image Button in your layout
An Image button can be created in XML (activity_main.xml) layout by using the <Imagebutton> tag as shown below:-
The image source for the above code is an image placed at the drawable folder with the name ic_users. You can specify your own image at that position.
Adding Function for Button Clicks
The OnClickListener is a function which is used to capture the event of clicking on a Image button and performing the desired task after the button is being clicked. To create this event handler, first create a View.OnClickListener object and then assign it to the Button by calling the setOnClickListener function. The corresponding function code for MainActivity.java file is shown below:-
Toast.makeText(ImageButton.this,"Thank You for clicking this picture",Toast.LENGTH_LONG).show();
The above code will create a variable of type Image Button and then call the OnClickListener to capture the event of that button being clicked. Once the event is captured,it will show a Toast on the screen, with the message “Thank You for clicking this picture”, once the user clicks on the button.
A sample image button is shown in the below picture. The button when clicked will display the message “Thanks for clicking this picture”.
The Full Java Code along with the XML layout for the above example is shown below:-
You can directly copy paste these snippets to your android studio, and they should work perfectly. Just save and run your project. You can also try to play with these other settings on your own and see the corresponding changes accordingly. There are a variety of properties available which can be changed to make your Image button more materialized and fancy looking.
For a more detailed guide, you can also visit android’s official guide below:-