11/17/09

Android Development: How To Add An Image Button

This application shows you how to add an imagebutton to your Android form and display a message using the Toast widget. A toast is a view containing a small message for the user. The toast class helps you create and show those. You can download the project file.


1. Create a new project
2. Open Main.xml in res/layout

3. Add a ImageButton to layout file main.xml

4. Set the Background property to an image in your project

5. Note the value for the imageButton ID

6. In ButtonActivity.java add the following code to the OnCreate() method. Make sure that R.id.ImageButton01 matches your imageButton’s ID.

final ImageButton button = (ImageButton) findViewById(R.id.android_button);
button.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
// Perform action on clicks
Toast.makeText(HelloFormStuff.this, "Beep Bop", Toast.LENGTH_SHORT).show();
}
});

7. Run application and select the image, “Beep Boo” message appears: Screen shot

2 comments:

  1. Where do you specify the image file?

    ReplyDelete
  2. Can you do the same for a widget, specifically the defining the click event.

    ReplyDelete