Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

Android 幀動畫實現方式詳解

編輯:Android 程式設計入門

幀動畫是 Android 中常見的動畫形式之一,它通過連續播放一系列圖片來呈現動畫效果。本文將介紹兩種實現幀動畫的方式:在 XML 文件中定義,以及通過 Java 代碼動態設置。

一、在 XML 文件中設置幀動畫

首先需要在 drawable 資源文件夾下創建一個 animation_list 文件,定義各幀的圖片與顯示時長:

<?xml version="1.0" encoding="utf-8"?> <animation-list xmlns:android="https://schemas.android.com/apk/res/android"> <item android:drawable="@drawable/p1" android:duration="500" /> <item android:drawable="@drawable/p2" android:duration="500" /> <item android:drawable="@drawable/p3" android:duration="500" /> <item android:drawable="@drawable/p4" android:duration="500" /> <item android:drawable="@drawable/p5" android:duration="500" /> </animation-list> 

然後在 Java 代碼中將動畫加載到控件上並啟動:

ImageView imageView=(ImageView)findViewById(R.id.id_iv); imageView.setImageResource(R.drawable.anim_list); AnimationDrawable animationDrawable = (AnimationDrawable) image.getDrawable(); animationDrawable.setOneShot(false);//是否只執行一次 animationDrawable.start();//開啟動畫 //animationDrawable.stop();//停止動畫 

二、在 Java 代碼中設置幀動畫

除了 XML 定義,也可以完全通過代碼動態添加每一幀:

ImageView imageView= (ImageView)findViewById(R.id.id_iv); animationDrawable= new AnimationDrawable(); animationDrawable.addFrame(getResources().getDrawable(R.drawable.p1), 500); animationDrawable.addFrame(getResources().getDrawable(R.drawable.p2), 500); imageView.setImageDrawable(animationDrawable); animationDrawable.setOneShot(false);//是否只執行一次 animationDrawable.start();//開啟動畫 //animationDrawable.stop();//停止動畫 

其中,addFrame 的兩個參數分別對應要顯示的圖片資源和該幀的顯示時長(毫秒)。setOneShot(false) 表示動畫循環播放,若設為 true 則只播放一次。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved