drawable 下创建animated_vector.xml
<?xml version="1.0" encoding="utf-8"?>
<animated-vector xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:drawable="@drawable/vector_drawable"
tools:ignore="NewApi">
<target
android:name="left"
android:animation="@animator/anim1"/>
<target
android:name="right"
android:animation="@animator/anim2"/>
</animated-vector>
animator下,anim1.xml
<objectAnimator
xmlns:android="http://schemas.android.com/apk/res/android"
android:duration="1000"
android:propertyName="translateX"
android:repeatMode="reverse"
android:repeatCount="infinite"
android:valueType="floatType"
android:valueFrom="0"
android:valueTo="10">
</objectAnimator>
anim2.xml
<objectAnimator
xmlns:android="http://schemas.android.com/apk/res/android"
android:duration="1000"
android:propertyName="translateX"
android:repeatMode="reverse"
android:repeatCount="infinite"
android:valueType="floatType"
android:valueFrom="0"
android:valueTo="-10">
</objectAnimator>
vector_drawable.xml
<vector xmlns:android="http://schemas.android.com/apk/res/android"
android:width="24dp"
android:height="24dp"
android:viewportWidth="24.0"
android:viewportHeight="24.0">
<group
android:name="left">
<path
android:fillColor="#FF000000"
android:pathData="M6.99,11L3,15l3.99,4v-3H14v-2H6.99v-3z,"/>
</group>
<group
android:name="right">
<path
android:fillColor="#FF000000"
android:pathData="M21,9l-3.99,-4v3H10v2h7.01v3L21,9z"/>
</group>
</vector>
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<ImageView
android:id="@+id/iv_demo"
android:layout_width="80dp"
android:layout_height="80dp"
app:srcCompat="@drawable/animated_vector"
tools:ignore="MissingConstraints" />
</androidx.constraintlayout.widget.ConstraintLayout>
Activity中的用法
public class MainActivity extends AppCompatActivity {
static{
AppCompatDelegate.setCompatVectorFromResourcesEnabled(true);
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
findViewById(R.id.iv_demo).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
ImageView view = (ImageView)v;
Drawable drawable = view.getDrawable();
if(drawable instanceof Animatable){
((Animatable) drawable).start();
}
}
});
}
}
activity
build.gradle中添加
defaultConfig {
vectorDrawables.useSupportLibrary = true
}