Using Drawables In TextViews

A common mistake I notice when reviewing Android development code is the use of more views than what is needed for the design. A good example of this is the use of three views (or more!) to create a very common pattern.

For instance, say the following was intended.

take_photo_buttonDevelopers have commonly implemented this using something that essentially has the following layout.

<RelativeLayout /* container */ >
   <ImageView /* image */  />
   <TextView /* text */ />
</RelativeLayout>

Android provides a much easier means to accomplish this. The same design above can be done using a single TextView.

<TextView
    android:id="@+id/take_photo_view"
    style="@style/TakePhotoView"
    android:drawableLeft="@drawable/camera_icon"
    android:background="@drawable/custom_border"
    android:text="Take photo" />

Since API level 1, TextView has allowed setting Drawables either to the left of, to the right of, above, or below the text. These Drawables, also know as Compound Drawables, can be specified in XML or using methods. In addition to location of where the Drawable is placed, you can also indicate the padding to use. Using this functionality on simple designs allows you to place an image near text without the need of an ImageView. In many cases, you can greatly simplify the amount of views needed to create your Android designs.