Explain Codes LogoExplain Codes Logo

How to programmatically set drawableLeft on Android button?

java
drawable
ui-ux
vector-drawables
Anton ShumikhinbyAnton Shumikhin·Aug 17, 2024
TLDR

Quickly add a drawable to the left of an Android button using this line:

button.setCompoundDrawablesWithIntrinsicBounds(R.drawable.icon, 0, 0, 0);

Here, button refers to your button object and R.drawable.icon to the drawable resource.

ContextCompat: Your one-way ticket to Drawable land

ContextCompat.getDrawable is the preferred practice, ensuring an easy ride across different Android versions:

Drawable leftImage = ContextCompat.getDrawable(context, R.drawable.image); button.setCompoundDrawablesWithIntrinsicBounds(leftImage, null, null, null);

The context is your current Android Activity or Application. And aren't we all contemplating on the context of our existence sometimes? 😂

Dress up your button: It’s not vanity, it’s UI/UX

Notify the users: Buttons can gossip too!

To change the drawable based on a certain state or event, let the button object 'gossip' the state of affairs.

if (eventOccurred) { Drawable eventDrawable = ContextCompat.getDrawable(context, R.drawable.event_icon); button.setCompoundDrawablesWithIntrinsicBounds(eventDrawable, null, null, null); } else { button.setCompoundDrawablesWithIntrinsicBounds(null, null, null, null); }

Like Picasso, but for Android: Using vector drawables

Vector drawables are your paint. build.gradle is your canvas. This is how Picasso would have done it if he was an Android Developer:

  1. Add this to build.gradle:

    android { defaultConfig { vectorDrawables.useSupportLibrary = true } }
  2. Before the masterpiece is created, call:

    AppCompatDelegate.setCompatVectorFromResourcesEnabled(true);

When size matters: Correctly scaling your drawables

If drawable doesn't fit, remember what Cinderella's godmother did: She adjusted the size. Here, you are the wizard:

Drawable leftIcon = ContextCompat.getDrawable(context, R.drawable.icon); leftIcon.setBounds(0, 0, width, height); button.setCompoundDrawables(leftIcon, null, null, null);

Note: Glass slippers are sold separately! 😉

Serve every patron: Different scenarios

The bouncer at the club: Permissions

Your drawable resource may need certain permissions for access. This applies when loading resources from the internet or the external storage.

Dependencies: What's a party without friends?

Check your build.gradle for necessary dependencies. Your drawables might be from an external library and dancing alone isn't much fun!

Kotlin: The other club across the street

In Kotlin, accessing and pinning drawableLeft on a button can be as concise:

val leftImage = ContextCompat.getDrawable(context, R.drawable.image) button.setCompoundDrawablesWithIntrinsicBounds(leftImage, null, null, null)