The ImageButton is a useful widget if you want to create a custom designed button. An ImageButton lets you specify a default, hover and disabled state (among others), each with a custom image of your choosing.
To create an ImageButton we need to:
- Add our images to our resources folder.
- Define a new ImageButton as an XML resource.
- Add our new button to our XML.
First step, add your images to the relevant drawable folders. You need at least a default button state, but it’s nice to add a “pressed” state too.
Second step is to create the XML definition of your button in res > drawable-somedpi > my_button.xml, replacing somedpi with any DPI of your choosing.
Use the following XML template as an example:
<?xml version="1.0" encoding="utf-8"?> <selector xmlns:android="http://schemas.android.com/apk/res/android"> <item android:drawable="@drawable/info_pressed" android:state_pressed="true" /> <item android:drawable="@drawable/info_pressed" android:state_focused="true" /> <item android:drawable="@drawable/info_enabled" android:state_enabled="true" /> <item android:drawable="@drawable/info_disabled" /> </selector>
The @drawable/somename entries refer to the images you previously added, without the file extension. In the above example, you can see I’ve defined the following:
- state_enabled: the default state of a newly created button in Android.
- A fallback “disabled” state. This will show when we disable the button later on.
Using an ImageButton
To use an ImageButton, you can define it in your XML view.
<ImageButton android:id="@+id/btnMyButton" android:layout_width="wrap_content" android:layout_height="wrap_content" android:background="@null" android:contentDescription="A description of my button" android:onClick="btnMyButton" android:src="@drawable/my_button" />
In the above example, I have defined:
- id — An ID for my button so we can refer to it later in our code if need be.
- background — Set to null to remove a solid background colour. This is useful when using PNG images to make sure the image doesn’t appear in a square box.
- contentDescription — This is the alt text, and is essential to make sure our app is accessible if the user is using accessibility tools.
- onClick — This points to a method in our activity that will be called when the button is clicked.
- src — This tells the ImageButton to use the settings we defined in my_button.xml.
If you want to disable an ImageButton so it can’t be clicked, you will need to do the following:
- Disable the button.
- Make the button unclickable.
This can’t be done in the view definition, but you can do it in your code:
ImageButton ib = (ImageButton)findViewById(R.id.btnMyButton); ib.setEnabled(false); ib.setClickable(false);
Android doesn’t provide a “disabled” state in our initial XML declaration so we need to ensure that the default button state in our definition is the disabled image. We can then specify a separate state_enabled image which will be used when the button is enabled.