Friday, December 14, 2012

Android beginner tutorial: Part 20 - ImageButton widget

Today we'll learn about the ImageButton widget.

The ImageButton component is similar to a regular Button, with the only exception that instead of text, it displays an image. If you haven't already read one of my earlier tutorials about ImageView class, do so, because in this tutorial we will be working with drawable resources.

Let's start writing our example application right away - go to activity_main.xml layout file and create a simple layout with an ImageButton inside of it. Use its android:src attribute to set the image source:

<LinearLayout xmlns:android=""
    tools:context=".MainActivity" >
    <ImageButton android:id="@+id/myButton"

I should note that in this tutorial I'm using 2 images - snowflake.png and snowflake2.png, which is basically a recolored version of the original snowflake.

Go to class now and create an Activity class that does the following things:

1. Declare 2 variables - "button" ImageButton and "toggle" boolean.
2. Set "toggle" to true in the onCreate() function.
3. Set "button" to our existing ImageButton in the layout xml.
4. Add a click listener to the button, which sets the image source of the button based on the "toggle" boolean value, also change the value of the "toggle" boolean to opposite.

Use the setImageResource() method to set image source dynamically.

Here's the code:

package com.kircode.codeforfood_test;

import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.widget.ImageButton;

public class MainActivity extends Activity{

public ImageButton button;
private boolean toggle;

protected void onCreate(Bundle savedInstanceState) {

toggle = true;

button = (ImageButton)findViewById(;
button.setOnClickListener(new View.OnClickListener() {

public void onClick(View v) {
toggle = !toggle;

public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(, menu);
return true;


If you run your application now on a device or an emulator, you'll see that you can press the button to toggle the image. Here's what my application looks like (2 screenshots of what the button looks like before and after clicking it):

Thanks for reading!

No comments:

Post a Comment