Question
Is it possible to use VectorDrawable in Buttons and TextViews with android:drawableRight, drawableStart, or drawableEnd?
<TextView
android:id="@+id/textView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:drawableRight="@drawable/ic_accessible_white_36px"
android:text="Hello World!"/>
Answer
Using VectorDrawables in TextViews and Buttons is a common practice in Android development for scalable UI designs. However, improper handling may lead to runtime crashes, especially when defining drawables in XML layout files. This guide explores how to use VectorDrawables safely in buttons and text views, particularly addressing the use of the drawable attributes such as android:drawableRight, drawableStart, and drawableEnd.
TextView tv = (TextView) findViewById(R.id.textView);
tv.setCompoundDrawablesWithIntrinsicBounds(null, null, getResources().getDrawable(R.drawable.ic_accessible_white_36px), null);
Causes
- Using a version of the support library that does not fully support VectorDrawables in XML.
- Misconfiguration in the gradle build setup preventing proper use of VectorDrawables.
- Using vector drawables without ensuring that the minimum SDK version meets necessary requirements.
Solutions
- Update your project to use the latest version of the Android support library that fully supports VectorDrawables (e.g., 28.0.0 or higher).
- Use `vectorDrawables.useSupportLibrary = true` in your `build.gradle` file to allow vector drawables to function correctly on lower API levels.
- If using deprecated drawable methods causes crashes, opt for programmatically setting the drawable, as shown in the provided example.
Common Mistakes
Mistake: Forgetting to enable vector support in the build.gradle file.
Solution: Add `vectorDrawables.useSupportLibrary = true` to your `buildTypes` in build.gradle.
Mistake: Using vector drawables without verifying minSdk version and the right approach for older devices.
Solution: Ensure the minSdkVersion is set to 21 or above and handle older versions with the appcompat library.
Mistake: Attempting to directly use SVG or vector XML resources in the layout which lead to crashes.
Solution: Always prefer setting drawables programmatically if experiencing issues or ensure all configurations are correct.
Helpers
- VectorDrawable
- Android TextView drawable
- VectorDrawables in Android
- DrawableRight in TextView
- Using SVG in Android