Is it possible to programmatically set drawableLeft?

In XML, we can set drawableLeft using this method:

    <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 the same programmatically?

+5
source share
2 answers

Yes use setCompoundDrawablesWithIntrinsicBounds

and determine the value 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 also created in the code, you need to use another setCompoundDrawablesWithIntrinsicBounds method , which takes 4 pictures and passes null for all but the left.

+16
source
+2

All Articles