文章导航
概述
Drawable Animation是逐帧动画,就像GIF图片,通过一系列Drawable依次显示来模拟动画的效果,那么使用它之前必须先定义好各个帧。我们可以通过代码定义,也可以使用xml文件定义,一般使用后者
动画定义
1 2 3 4 5 6 7
| <animation-list xmlns:android="http://schemas.android.com/apk/res/android" android:oneshot="true"> <item android:drawable="@drawable/frame_1" android:duration="200" /> <item android:drawable="@drawable/frame_2" android:duration="200" /> <item android:drawable="@drawable/frame_3" android:duration="200" /> <item android:drawable="@drawable/frame_4" android:duration="200" /> </animation-list>
|
其中android:oneshot="true"表示该动画只播放一次,等于false时则循环播放
平常我们加载中动画就可以这样实现
有时我们想每一帧是由多个图片组成怎么办
1 2 3 4 5 6 7 8 9
| <animation-list xmlns:android="http://schemas.android.com/apk/res/android" android:oneshot="true"> <item android:duration="100"> <layer-list> <item android:drawable="@drawable/login_loading_00" /> <item android:drawable="@drawable/login_loading_10" /> </layer-list> </item> </animation-list>
|
这样图片就一层层的叠起来了
动画调用
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39
| public class MainActivity extends Activity { private AnimationDrawable loadingAnimation;
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main); ImageView loadingImg = (ImageView) findViewById(R.id.loading); loadingImg.setBackgroundResource(R.drawable.loading); loadingAnimation = (AnimationDrawable) loadingImg.getBackground(); }
public boolean onTouchEvent(MotionEvent event) { if (event.getAction() == MotionEvent.ACTION_DOWN) { loadingAnimation.stop(); return true; } return super.onTouchEvent(event); }
@Override public void onWindowFocusChanged(boolean hasFocus) { super.onWindowFocusChanged(hasFocus); if (hasFocus) loadingAnimation.start(); }
}
|
需要注意的是,不能在onCreate()方法中调用AnimationDrawable的start()方法,因为此时AnimationDrawable还未真正加载到界面中。所以,如果想启动界面就自动运行动画,可以在OnWindowFocusChanged(boolean hasFocus)中启动动画。