Saturday, March 24, 2012

How to set the drawableRight resource by code?

     Sometimes we want to include a small icon inside a Button, how to achieve this?



Prepare your PNG file and put it your res/drawable folder along with the other image resources in your application.

just like any other view handling - this can be done by Code or by XML.

By XML

                   <Button
                       android:id="@+id/buttonId"
                       android:layout_width="wrap_content"
                       android:layout_height="wrap_content"
                       android:layout_gravity="center"
                       android:drawableRight="@drawable/timer_red"
                       android:text="@string/some_text"
                    />
this is good for an initial state of the button, in some cases it will change dynamically to other icon (change position within the button etc..)


By Code

btTimer.setCompoundDrawablesWithIntrinsicBounds
(0, 0,R.drawable.timer_red, 0);

0's are in the directions in which we don't want to show a Drawable.

in this manner we can easily create buttons with indicators.