Векторная анимация в приложениях android (Animated Vector Drawable)

Как использовать векторную анимацию (Animated Vector Drawable) в андроид-приложениях. Как загрузть в приложение android свою векторную картинку и как анимировать векторные изображения.

На прошлом уроке по дизайну андроид-приложений мы говорили об использовании векторной графики и научились создавать векторные ресурсы в Андроид Студио.

На этом уроке загрузим в приложение свою векторную картинку и научимся анимировать векторные изображения. Исходный код под видео.

<vector xmlns:android="http://schemas.android.com/apk/res/android"
    android:width="500dp"
    android:height="500dp"
    android:viewportHeight="500"
    android:viewportWidth="500">

    <group android:name="head">
    <path
        android:fillColor="#9FBF3B"
        android:pathData="M301.3,83.3l20.2,-29.3c1.2,-1.7 0.9,-4 -0.7,-5.1c-1.6,-1.1 -3.8,-0.5 -5,1.2L294.9,80.5c-13.8,-5.4 -29.1,-8.5 -45.3,-8.5c-16.2,0 -31.5,3 -45.3,8.5l-20.9,-30.4c-1.2,-1.7 -3.4,-2.3 -5,-1.2c-1.6,1.1 -1.9,3.4 -0.7,5.1l20.2,29.3c-32.1,14.9 -54.5,43.3 -57.4,76.3h218.3C355.9,126.6 333.4,98.2 301.3,83.3" />


    <path
        android:name="blink_left"
        android:fillColor="#FFFFFF"
        android:pathData="M204,129.4c-6.7,0 -12.1,-5.4 -12.1,-12.1c0,-6.7 5.4,-12.1 12.1,-12.1c6.7,0 12.1,5.4 12.1,12.1C216,124 210.6,129.4 204,129.4" />
    <path
        android:name="blink_right"
        android:fillColor="#FFFFFF"
        android:pathData="M295.2,129.4c-6.7,0 -12.1,-5.4 -12.1,-12.1c0,-6.7 5.4,-12.1 12.1,-12.1c6.7,0 12.1,5.4 12.1,12.1C307.2,124 301.8,129.4 295.2,129.4" />

    <path
        android:fillColor="#9FBF3B"
        android:pathData="M126.4,297.6c0,13.4 -10.9,24.4 -24.4,24.4l0,0c-13.4,0 -24.4,-10.9 -24.4,-24.4V199.1c0,-13.4 10.9,-24.4 24.4,-24.4l0,0c13.5,0 24.4,10.9 24.4,24.4V297.6z" />
   <path
        android:fillColor="#9FBF3B"
        android:pathData="M372.7,297.6c0,13.4 10.9,24.4 24.4,24.4l0,0c13.4,0 24.4,-10.9 24.4,-24.4V199.1c0,-13.4 -10.9,-24.4 -24.4,-24.4l0,0c-13.5,0 -24.4,10.9 -24.4,24.4V297.6z" />
    </group>
    <path
        android:fillColor="#9FBF3B"
        android:pathData="M140.4,175.5v177.9c0,10.6 8.6,19.1 19.1,19.1h22.6v54.7c0,13.5 10.9,24.4 24.4,24.4c13.5,0 24.4,-10.9 24.4,-24.4v-54.7h37.4v54.7c0,13.5 10.9,24.4 24.4,24.4s24.4,-10.9 24.4,-24.4v-54.7h22.6c10.6,0 19.1,-8.6 19.1,-19.1V175.5H140.4z" />

</vector>
<?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/android"
    tools:ignore="NewApi">
    
    <target
        android:animation="@animator/blink_left"
        android:name="blink_left" />
    <target
        android:animation="@animator/blink_right"
        android:name="blink_right" />
    <target
        android:animation="@animator/head_up"
        android:name="head" />

</animated-vector>
<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android">
    <objectAnimator
        android:duration="400"
        android:repeatCount="infinite"
        android:repeatMode="reverse"
        android:valueFrom="#FFFFFF"
        android:valueTo="#9FBF3B"
        android:valueType="colorType"
        android:propertyName="fillColor"/>

</set>
<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android">
    <objectAnimator
        android:duration="400"
        android:propertyName="translateY"
        android:repeatCount="infinite"
        android:repeatMode="reverse"
        android:valueFrom="0"
        android:valueTo="-10"
        android:valueType="floatType" />

</set>
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    app:layout_behavior="@string/appbar_scrolling_view_behavior"
    tools:context="info.fandroid.myapplication.MainActivity"
    tools:showIn="@layout/app_bar_main">

    <ImageView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        app:srcCompat="@drawable/ic_android_green_240dp"
        tools:ignore = "MissingPrefix"/>
    <ImageView
        android:id="@+id/android_anim"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        app:srcCompat="@drawable/anim_android"
        tools:ignore="MissingPrefix" />


</LinearLayout>
apply plugin: 'com.android.application'

android {
    compileSdkVersion 23
    buildToolsVersion "23.0.2"

    defaultConfig {
        applicationId "info.fandroid.myapplication"
        minSdkVersion 14
        targetSdkVersion 23
        versionCode 1
        versionName "1.0"
        vectorDrawables.useSupportLibrary = true
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    testCompile 'junit:junit:4.12'
    compile 'com.android.support:appcompat-v7:23.2.0'
    compile 'com.android.support:design:23.2.0'
    compile 'com.android.support:support-vector-drawable:23.2.0'
    compile 'com.android.support:animated-vector-drawable:23.2.0'

}
package ...;

import android.graphics.drawable.Animatable;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.NavigationView;
import android.support.design.widget.Snackbar;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.app.AppCompatDelegate;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ImageView;

public class MainActivity extends AppCompatActivity
        implements NavigationView.OnNavigationItemSelectedListener {
    private ImageView mAnimAndroid;

    static {
        AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_AUTO);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        mAnimAndroid = (ImageView) findViewById(R.id.android_anim);

        FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
                        .setAction("Action", null).show();
            }
        });

        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
                this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
        drawer.setDrawerListener(toggle);
        toggle.syncState();

        NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
        navigationView.setNavigationItemSelectedListener(this);
    }

    @Override
    protected void onResume() {
        super.onResume();
        Drawable drawable = mAnimAndroid.getDrawable();
        if (drawable instanceof Animatable){
            ((Animatable) drawable).start();
        }


    }

    @Override
    public void onBackPressed() {
        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        if (drawer.isDrawerOpen(GravityCompat.START)) {
            drawer.closeDrawer(GravityCompat.START);
        } else {
            super.onBackPressed();
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    @SuppressWarnings("StatementWithEmptyBody")
    @Override
    public boolean onNavigationItemSelected(MenuItem item) {
        // Handle navigation view item clicks here.
        int id = item.getItemId();

        if (id == R.id.nav_camera) {
            // Handle the camera action
        } else if (id == R.id.nav_gallery) {

        } else if (id == R.id.nav_slideshow) {

        } else if (id == R.id.nav_manage) {

        } else if (id == R.id.nav_share) {

        } else if (id == R.id.nav_send) {

        }

        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        drawer.closeDrawer(GravityCompat.START);
        return true;
    }
}

 

Коментарі: 3
  1. Михаил

    При анимации вылетает клас каст ексепшин, но почему?
    switch_circle.xml


    AppCompatImageButton switchCircle = (AppCompatImageButton) view.findViewById(R.id.switchButtonCircle);
    Drawable drawable = switchCircle.getDrawable();
    ((Animatable) drawable).start();

    switch_circle_animated_vector.xml


    filling.xml


    image button


    stacktrace

    java.lang.ClassCastException: android.graphics.drawable.VectorDrawable cannot be cast to android.graphics.drawable.Animatable
    at com.plorial.telegramcamera.CameraPreviewFragment$1.onClick(CameraPreviewFragment.java:65)
    at android.view.View.performClick(View.java:5198)
    at android.view.View$PerformClick.run(View.java:21147)
    at android.os.Handler.handleCallback(Handler.java:739)
    at android.os.Handler.dispatchMessage(Handler.java:95)
    at android.os.Looper.loop(Looper.java:148)
    at android.app.ActivityThread.main(ActivityThread.java:5417)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)

Додати коментар