Adding drawables
Drawables can only be added programmatically using Java/Kotlin code. You cannot add drawables via XML attributes.Drawables are added using
SpannableString and ImageSpan internally, which provides better control over icon positioning and sizing.Left drawable
Basic usage
Add a drawable to the left of the button text using default dimensions:The drawable resource ID (e.g.,
R.drawable.ic_check)Custom dimensions
Add a drawable with custom width and height:The drawable resource ID
Drawable width in pixels
Drawable height in pixels
Right drawable
Basic usage
Add a drawable to the right of the button text using default dimensions:The drawable resource ID (e.g.,
R.drawable.ic_arrow_forward)Custom dimensions
Add a drawable with custom width and height:The drawable resource ID
Drawable width in pixels
Drawable height in pixels
Complete example
Here’s a complete example showing how to create a button with customization and a left drawable:Best practices
Use vector drawables
Use vector drawables
Prefer vector drawables (XML vectors) over PNG images for better scalability across different screen densities. Vector drawables are supported through
AppCompatDelegate.setCompatVectorFromResourcesEnabled(true) in CustomButton.Size drawables appropriately
Size drawables appropriately
For best results, use icon sizes between 18dp and 24dp. Convert to pixels based on screen density to ensure consistent sizing.
Consider text length
Consider text length
Be mindful of button text length when adding drawables. Long text with large drawables may cause layout issues or text truncation.
Match icon style
Match icon style
Ensure your drawable icons match your button style (filled vs outlined) and overall app design language.
Test both orientations
Test both orientations
Test buttons with drawables in both portrait and landscape orientations to ensure they display correctly in all scenarios.
Drawable alignment
Drawables are aligned to the bottom of the text usingImageSpan.ALIGN_BOTTOM. This ensures consistent vertical alignment with the button text.
The library uses
SpannableString internally to add drawables. Calling setDrawableLeft() or setDrawableRight() modifies the button’s text content by inserting the drawable as a span.Limitations
- You cannot add both left and right drawables to the same button simultaneously
- Calling
setDrawableLeft()aftersetDrawableRight()will replace the right drawable with a left one - Drawables cannot be added via XML attributes
- The library does not support top or bottom drawables
Next steps
Button styles
Explore pre-configured button styles
Customization
Learn how to customize colors and appearance