September 28, 2013

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.

Image of take photo button

<pre class="EnlighterJSRAW" data-enlighter-language="xml"><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.

<pre class="EnlighterJSRAW" data-enlighter-language="xml"><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.

— Onyx