Reputation: 57
I used vector selector drawable in xml which works well, but crash in Java code when sdk < 21.
Here is my xml usage:
<android.support.v7.widget.AppCompatTextView
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:drawableLeft="@drawable/common_selector_ic_back"/>
common_selecor_ic_back.xml
<selector
xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="@drawable/common_ic_back" />
</selector>
common_ic_back.xml
<vector xmlns:android="http://schemas.android.com/apk/res/android"
android:width="24dp"
android:height="24dp"
android:viewportHeight="24.0"
android:viewportWidth="24.0">
<path
android:fillColor="#FFFFFFFF"
android:pathData="M20,11H7.83l5.59,-5.59L12,4l-8,8 8,8 1.41,-1.41L7.83,13H20v-2z"/>
But I want to change the drawableLeft in code, I tried three solution, both failed.
1
Drawable d1 = getResources().getDrawable(R.drawable.common_selector_ic_back);
crashed with
android.content.res.Resources$NotFoundException: File res/drawable/common_selector_ic_back.xml from drawable resource ID
0x7f080065
2
icon2 = AppCompatResources.getDrawable(this, R.drawable.common_selector_ic_back);
failed with same reason
3
VectorDrawableCompat.create(context.getResources(), R.drawable.common_selector_ic_back, context.getTheme());
failed with log
Binary XML file line #2 tag requires viewportWidth > 0
Any one meet the problem? Can you tell me how to get vector selector drawable in hardware code.
Solution:
The activity must be AppCompatActivity
Upvotes: 0
Views: 197
Reputation: 10125
Solution: Try these steps below:
First, Add this line in your common_ic_back.xml
<vector
...
android:tintMode="multiply"
...>
......
......
</vector>
Then, Don't forget to add build.gradle(Module:app)
or the approach will not work on old Android versions.
defaultConfig {
....
vectorDrawables.useSupportLibrary = true
....
}
Lastly, add this in you activity
class, before onCreate()
where you are using this vector:
static {
AppCompatDelegate.setCompatVectorFromResourcesEnabled(true);
}
Try it. Hope it helps. Please comment if any doubts.
Upvotes: 0