, , , , , , , , , ,

Many a times we tend to add an image to a text for a Button. The pictorial representation of an action is easier for the user to understand and provides a visual identity for the application. In Android, there is a general perception that this has needs a minimum of three views.

Compound Drawable

    <LinearLayout android:orientation="horizontal">
         <ImageView ... the icon ... />
         <TextView ... the text ... />

However, Android provides a way to add combine these views into a single view — a TextView. TextViews can optionally support Drawables in a view. They can be specified in XML or using Java methods. From the likes of it, based on the naming convention used, they wanted an approach to show borders like in HTML. However, they can be hacked to show much more than borders.

    <TextView android:text=" ... the text ... "

The Drawable can be assigned to any direction, and more than one can be specified at a time. The distance between the drawable and the text is specified by the attribute android:drawablePadding. Unfortunately, the padding has to be the same on all sides. Also, this padding is different from the TextView’s padding. By default the image is shown at its actual size. What if the icon is huge and we don’t want it to be bigger than the text? Using Drawable’s setBounds(), we can set the size of the Canvas to use to render the Drawable. A drawable that is assigned as a compound drawable for a TextView should have its bounds set before being specified as one. The standard Android’s launcher uses this approach to show the icons with the name of the app. The menu items are also rendered in the same way. Though this doesn’t scale well for all purposes, for simpler cases, this reduces the views effectively.