Image Button

A button with a custom image on it. We'll make it display a message when pressed.

1. Drag the Android image on the right (or your own image) into the res/drawable/ directory of your project. We'll use this for the button.

2. Open the layout file and, inside the LinearLayout, add the ImageButton element:

<ImageButton android:id="@+id/android button" android:layout width="100dip" android:layout height="wrap content" android:src="@drawable/android" />

The source of the button is from the res/drawable/ directory, where we've placed the android.png.

Tip: You can also reference some of the many built-in images from the Android R.drawable resources, like ic media play, for a

"play" button image. To do so, change the source attribute toandroid:src="@android:drawable/ic media play".

3. To make the button to actually do something, add the following code at the end of the onCreate() method:

final ImageButton button = (ImageButton) findViewById( button);

button.setOnClickListener(new OnClickListener() { public void onClick(View v) {

// Perform action on clicks

Toast.makeText(HelloFormStuff.this, "Beep Bop",

This captures our ImageButton from the layout, then adds an on-click listener to it. The View.OnClickListener must define the onClick() method, which defines the action to be made when the button is clicked. Here, we show a Toast message when clicked.

0 0


  • taimi
    How to display a image button on tabwidget in android?
    7 years ago

Post a comment