确保您正在使用AppCompatActivity
并不是Activity
。如果您正在使用Activity
,然后在您的活动/片段中写入:
imageView.setImageResource(R.drawable.ic_svg_image);
还添加build.gradle
:
android {
defaultConfig {
vectorDrawables.useSupportLibrary = true
}
}
对于 4.x 版本的 Android,您还可以添加对TextView
s' 的内部可绘制对象。这也是实际的ImageView
s.
public class MyApplication extends Application {
@Override
public void onCreate() {
super.onCreate();
// This flag should be set to true to enable VectorDrawable support for API < 21.
AppCompatDelegate.setCompatVectorFromResourcesEnabled(true);
}
}
然后在AndroidManifest中添加这个文件:
<application
android:name=".MyApplication"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
...
</application>
有时它会破坏一些旧设备。然后将您的可绘制对象包裹在里面:
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="@drawable/ic_svg_image/>
</selector>
并设置它而不是 SVG:
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:srcCompat="@drawable/drawable"
/>