Android中實現一個簡單的逐幀動畫(附代碼下載)


場景

Android中的逐幀動畫,就是由連續的一張張照片組成的動畫。

效果

 

 

注:

博客:
https://blog.csdn.net/badao_liumang_qizhi
關注公眾號
霸道的程序猿
獲取編程相關電子書、教程推送與免費下載。

實現

首先准備一組不同表情的照片,放在res/drawable下,然后在此目錄下新建動畫資源文件fairy.xml

<?xml version="1.0" encoding="utf-8"?>
<animation-list xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:drawable="@drawable/img001" android:duration="60"/>
    <item android:drawable="@drawable/img002" android:duration="60"/>
    <item android:drawable="@drawable/img003" android:duration="60"/>
    <item android:drawable="@drawable/img004" android:duration="60"/>
    <item android:drawable="@drawable/img005" android:duration="60"/>
    <item android:drawable="@drawable/img006" android:duration="60"/>
</animation-list>

 

這里是逐幀動畫,所以節點是animation-list 。

然后來到布局文件,將布局設置為LinearLayout並添加id屬性,並且設置背景為上面添加的動畫資源文件

<?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:layout_width="match_parent"
    android:id="@+id/linearLayout"
    android:orientation="vertical"
    android:background="@drawable/fairy"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

 

</LinearLayout>

 

然后來到對應的Activity,創建標識變量Flag,然后獲取AnimationDrawable對象,並且為布局管理器添加單擊事件。從而控制動畫的停止和播放。

package com.badao.animationtest;

import androidx.appcompat.app.AppCompatActivity;

import android.graphics.drawable.AnimationDrawable;
import android.os.Bundle;
import android.view.View;
import android.widget.LinearLayout;

public class MainActivity extends AppCompatActivity {

    private boolean flag = true;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        LinearLayout linearLayout= (LinearLayout) findViewById(R.id.linearLayout); //獲取布局管理器
        //獲取AnimationDrawable對象
        final AnimationDrawable anim= (AnimationDrawable) linearLayout.getBackground();
        linearLayout.setOnClickListener(new View.OnClickListener() {  //為布局管理器添加單擊事件
            @Override
            public void onClick(View v) {
                if(flag){
                    anim.start(); //開始播放動畫
                    flag=false;
                }else {
                    anim.stop();  //停止播放動畫
                    flag=true;
                }
            }
        });
    }
}

 

代碼下載

https://download.csdn.net/download/BADAO_LIUMANG_QIZHI/12097211


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM