How to use Compound drawables in your android app design

A Small Design tip: Compound Drawables.

A question by our reader
I designed a layout which worked perfectly well, but I updated to ADT 16 and the new Lint tool gave me a warning 
"This tag and its children can be replaced by one and a compound drawable."

In this article we’ll have a look at what they are and see how we can use them to simplify some of our layouts.


custom drawable androidgreeve


A quick dig through the documentation for TextView lead me to the setCompoundDrawableWithIntrinsicBounds() method which is a method of attaching drawables to a TextView. We can replace the LinearLayout and its two children with a single TextView:

How to use it:
<TextView

android:id="@+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/text"
android:gravity="center"/>




Then in the onCreate() method of our activity we can assign a drawable to appear above the the text.

@Override
public void onCreate( Bundle savedInstanceState )
{
    super.onCreate( savedInstanceState );
    setContentView( R.layout.main );
    TextView tv = (TextView) findViewById( R.id.textView );
    tv.setCompoundDrawablesWithIntrinsicBounds( 0,
        R.drawable.ic_launcher, 0, 0 );
}

Our TextView has four properties that let us specify images to be set around it. These ones are: drawableLeft, drawableRight, drawableTop and drawableBottom. We also can use another one which defines the padding among the text and the images: drawablePadding.
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="16dp"
android:gravity="center"
android:layout_gravity="center_horizontal"
android:text="@string/my_contacts"
android:drawableRight="@drawable/ic_action_add_group"
android:drawablePadding="8dp"
/>



Cool! We removed a level of complexity and made our XML much simpler. It’s almost as easy to set these drawables from code:

textView.setCompoundDrawablesWithIntrinsicBounds
(0, 0, R.drawable.ic_action_add_group, 0);

textView.setCompoundDrawablePadding(...);

There are plenty of other use cases where compound drawables can simplify your layouts. If you use the Lint tool in ADT 16+ you will be alerted to instances where you can make this optimisation. It my only sound like a small improvement to create one Widget instead of three, but if we expand this to the layout that we created in Intelligent Layouts.
What Next ?
We would like to Demonstrate this by designing a small Login page for our app.

Hey I'm Venkat
Developer, Blogger, Thinker and Data scientist. nintyzeros [at] gmail.com I love the Data and Problem - An Indian Lives in US .If you have any question do reach me out via below social media


EmoticonEmoticon