Android TextView with Icon: Enhance App UI with Ease
Android's TextView is a fundamental UI element, often used to display text. Adding an icon to a TextView is a common task in Android app development, enhancing the UI's aesthetics and functionality. This article guides you through displaying an icon beside TextView text seamlessly.
Before digging into the code, ensure you've added the desired drawable in your project's res/drawable folder. For this example, let's use a typical icon named 'icon.png'.
Using DrawableLeft and DrawableRight Properties
The TextView includes DrawableLeft and DrawableRight properties, allowing you to attach an icon to either the left or right side of the text. Here's how you can do it:
First, add the icon to your TextView in XML:
```xmlIn the above XML snippet, replace 'Text' with your desired text and 'icon' with your drawable's name.
Changing Drawable Type
By default, DrawableLeft and DrawableRight properties place the icon in the middle of TextView. You can change the icon's position by changing the drawable type:
- drawableStart: Places the icon at the beginning (left).
- drawableTop: Places the icon above the text.
- drawableEnd: Places the icon at the end (right).
- drawableBottom: Places the icon below the text.
So, to place the icon at the start, use android:drawableStart="@drawable/icon".
Changing Icon Size and Padding
You can change the icon's size using android:drawablePadding and android:layout_width or android:layout_height properties:
```xmlIn this example, the drawable's padding is set to 4dp, and the TextView's padding is set to 10dp from the left, effectively pushing the icon away from the text.
Using Compound Drawables in TextView
Compound drawables enable you to place an icon(s) at relative positions within a TextView. They provide more flexibility in adjusting icon/text layout.
To use compound drawables, you'll need to set the android:drawable* and android:compoundDrawablePadding properties. Here's an example:
```xmlThe android:compoundDrawablePadding property adds extra space between the text and the drawable. In this case, it adds a 10dp space to the left of the text.
Conclusion
Now you're equipped to add icons to your TextViews to enhance your app's user interface. Whether you opt for simple DrawableLeft and DrawableRight properties or the more flexible compound drawables, your app's users will appreciate the visual cues that icons provide. Happy coding! Dive into your project and start leveraging these TextView enhancements.