How to programmatically set drawableLeft on Android button?
Quickly add a drawable to the left of an Android button using this line:
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:
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.
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:
-
Add this to
build.gradle
: -
Before the masterpiece is created, call:
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:
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:
Was this article helpful?