Recipe 2.2 Using Image Buttons

Android Versions
Level 1 and above
Permissions
None
Source Code to Download from Wrox.com
ImageButtons.zip

The previous recipe showed the Button and ToggleButton in action and the various ways to handle their events. This recipe describes how to display images on buttons. As the saying goes, a picture is worth a thousand words. Hence, sometimes it would be more intuitive and descriptive to display a picture on top of a button rather than words.

Solution

Consider the following code snippet in the activity_main.xml file:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" > <ImageButton android:id="@+id/imageButton" android:layout_width="wrap_content" android:layout_height="wrap_content" android:src="@drawable/ic_launcher" android:onClick="onToggle" /> <Button android:id="@+id/imageTextButton1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:drawableTop="@drawable/ic_launcher" android:text="Android"/> <Button android:id="@+id/imageTextButton2" android:layout_width="wrap_content" android:layout_height="wrap_content" android:drawableLeft="@drawable/ic_launcher" android:text="Android"/> <Button android:id="@+id/imageTextButton3" android:layout_width="wrap_content" android:layout_height="wrap_content" android:drawableRight="@drawable/ic_launcher" android:text="Android"/> <Button ...

Get Android Application Development Cookbook: 93 Recipes for Building Winning Apps now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.