AnimationDrawable是Android实现动画的一种简单的形式,可以用来实现帧动画。

1.在res/drawable下定义friend.xml文件:

[java] view plain copy
  1. <?xmlversion="1.0"encoding="utf-8"?>
  2. <animation-listandroid:oneshot="false"
  3. xmlns:android="http://schemas.android.com/apk/res/android">
  4. <itemandroid:duration="400"android:drawable="@drawable/friend_light"/>
  5. <itemandroid:duration="400"android:drawable="@drawable/friend"/>
  6. </animation-list>
其中,每一个item是一帧,android:duration="400"表示每帧持续400ms,android:drawable是每帧要显示的图片。

2.在java代码中载入和执行动画:

①载入动画

[java] view plain copy
  1. Buttonfriend=(Button)findViewById(R.id.friend_btn);
  2. friend.setBackgroundResource(R.drawable.friend_anim);
  3. AnimationDrawablefriend_anim=(AnimationDrawable)friend.getBackground();

②执行动画

[java] view plain copy
  1. friend_anim.start();
③停止动画

[java] view plain copy
  1. friend_anim.stop();

3. 注意:

默认情况下,在OnCreate()中执行animation.start();是无效的,因为在OnCreate()中AnimationDrawable还没有完全的与ImageView绑定,在OnCreate()中启动动画,就只能看到第一张图片。

解决办法:

①调用View的getViewTreeObserver().addOnPreDrawListener()

[java] view plain copy
  1. friend.getViewTreeObserver().addOnPreDrawListener(newOnPreDrawListener(){
  2. @Override
  3. publicbooleanonPreDraw(){
  4. //TODOAuto-generatedmethodstub
  5. friend_anim.start();
  6. returntrue;
  7. }
  8. });

②使用Handler

[java] view plain copy
  1. publicvoidonCreate(BundlesavedInstanceState){
  2. super.onCreate(savedInstanceState);
  3. setContentView(R.layout.main);
  4. friend=(Button)findViewById(R.id.friend_btn);
  5. handler.postDelayed(newRunnable(){
  6. publicvoidrun(){
  7. friend.setBackgroundResource(R.drawable.friend_anim);
  8. friend_anim=(AnimationDrawable)friend.getBackground();
  9. friend_anim.start();
  10. }
  11. },50);
  12. }

更多相关文章

  1. (翻译)Android中的定时任务
  2. android 动画深入分析(一)《android开发艺术与探索》
  3. animation的xml定义中的android:interpolator属性
  4. 2011.07.18(4)——— android 播放gif
  5. android视图切换动画:ViewAnimator类及其子类
  6. 2011.07.18(2)——— android Animation的另一种运行
  7. Android(安卓)运行 Linux 可执行程序
  8. 2011.07.18(2)——— android Animation的另一种运行
  9. Android(安卓)实现 按钮从两边移到中间动画效果

随机推荐

  1. Android 应用程序权限
  2. Android webview与js交换JSON对象数据示
  3. Android周学习Step By Step(6)--Android的
  4. Android中Animator & Animation比较
  5. Android 通知(Notification)高级用法和注
  6. Android如何判断系统是不是首次开机
  7. [置顶] Android中数据存储的5种方法
  8. 【Android】关于TextView
  9. android WebView组件使用总结
  10. Android: IllegalStateException: databa