AnimationImageView帧动画结束.java 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. package com.example.animationtest.ui;
  2. import android.content.Context;
  3. import android.graphics.drawable.AnimationDrawable;
  4. import android.os.Handler;
  5. import android.util.AttributeSet;
  6. import android.widget.ImageView;
  7. /**
  8. * 自定义ImageView
  9. * @author 1234
  10. * 可以播放动态图片
  11. */
  12. public class AnimationImageView extends ImageView {
  13. public AnimationImageView(Context context, AttributeSet attrs, int defStyle) {
  14. super(context, attrs, defStyle);
  15. }
  16. public AnimationImageView(Context context, AttributeSet attrs) {
  17. super(context, attrs);
  18. }
  19. public AnimationImageView(Context context) {
  20. super(context);
  21. }
  22. public interface OnFrameAnimationListener{
  23. /**
  24. * 动画开始播放后调用
  25. */
  26. void onStart();
  27. /**
  28. * 动画结束播放后调用
  29. */
  30. void onEnd();
  31. }
  32. /**
  33. * 不带动画监听的播放
  34. * @param resId
  35. */
  36. public void loadAnimation(int resId){
  37. setImageResource(resId);
  38. AnimationDrawable anim = (AnimationDrawable)getDrawable();
  39. anim.start();
  40. }
  41. /**
  42. * 带动画监听的播放
  43. * @param resId
  44. * @param listener
  45. */
  46. public void loadAnimation(int resId, final OnFrameAnimationListener listener) {
  47. setImageResource(resId);
  48. AnimationDrawable anim = (AnimationDrawable)getDrawable();
  49. anim.start();
  50. if(listener != null){
  51. // 调用回调函数onStart
  52. listener.onStart();
  53. }
  54. // 计算动态图片所花费的事件
  55. int durationTime = 0;
  56. for (int i = 0; i < anim.getNumberOfFrames(); i++) {
  57. durationTime += anim.getDuration(i);
  58. }
  59. // 动画结束后
  60. Handler handler = new Handler();
  61. handler.postDelayed(new Runnable() {
  62. @Override
  63. public void run() {
  64. if(listener != null){
  65. // 调用回调函数onEnd
  66. listener.onEnd();
  67. }
  68. }
  69. }, durationTime);
  70. }
  71. }