Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to set drawableLeft programmatically?

Tags:

android

In XML we can set drawableLeft using this way:

    <Button
    android:id="@+id/previewBtn"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:background="@drawable/white_btn"
    android:drawableLeft="@drawable/green_circle"
    android:drawablePadding="16dp"
    android:text="Button" />

How to do same thing programmatically?

like image 339
Dmitry Zaytsev Avatar asked May 08 '12 20:05

Dmitry Zaytsev


People also ask

How can change button background drawable programmatically in Android?

How to set Background of button in Android programmatically? setBackgroundResource() method is used to change the button background programmatically. setBackgroundResource(int id) accepts id of drawable resource and applies the background to the button.

What is a drawable?

A drawable resource is a general concept for a graphic that can be drawn to the screen and which you can retrieve with APIs such as getDrawable(int) or apply to another XML resource with attributes such as android:drawable and android:icon . There are several different types of drawables: Bitmap File.


2 Answers

Yes, use setCompoundDrawablesWithIntrinsicBounds

and define the drawable for the first parameter, then 0 for all the others.

The code should look something like this:

Button b = findViewById(R.id.myButton);

b.setCompoundDrawablesWithIntrinsicBounds(R.drawable.myDrawable, 0, 0, 0);

If your drawable was created in code as well then you need to use the other setCompoundDrawablesWithIntrinsicBounds method which takes 4 drawables, and pass null for all but the left.

like image 102
Matt Wolfe Avatar answered Oct 23 '22 23:10

Matt Wolfe


The method to use is setCompoundDrawablesWithIntrinsicBounds. This method takes all four drawable options (left, top, right, bottom), so if you want only left, pass in null for the others.

like image 38
wsanville Avatar answered Oct 23 '22 22:10

wsanville