Wednesday, September 28, 2011

Android Custom ImageView Frame Animation

StarTwinkleImageView.java
package com.dearpeople.android.test.ani;
import android.content.Context;
import android.graphics.drawable.AnimationDrawable;
import android.util.AttributeSet;
import android.widget.ImageView;

public class StarTwinkleImageView extends ImageView {
 AnimationDrawable animation;
 public StarTwinkleImageView(Context context, AttributeSet attrs) {
  super(context, attrs);
  startAnimation();
 }

   /* 내부클래스, UI 쓰레드가 실행할 코드(Runnable)를 작성한다 */
   class Starter implements Runnable {
       // UI쓰레드는 Runnable객체를 받아서 실행하면 애니메이션이 시작된다
       public void run() {
           animation.start();
       }
   }
  
   private void startAnimation(){
       // 각 프레임을 저장할 객체를 생성한다
       animation = new AnimationDrawable();
      
       // 각 프레임으로 사용할 이미지를 등록한다
       animation.addFrame(getResources().getDrawable(R.drawable.t04_09_mpost_main_event_icon_1), 100);
       animation.addFrame(getResources().getDrawable(R.drawable.t04_09_mpost_main_event_icon_2), 100);
      
       //애니메이션을 한번만 실행할 것인지 반복할 것인지 설정한다
       animation.setOneShot(false);
       //애니메이션이 실행될 공간을 확보한다
       this.setBackgroundResource(R.drawable.t04_09_mpost_main_event_icon_1);
       this.setImageDrawable(animation);
       this.post(new Starter());
   }
}


main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
 android:id="@+id/linearLayout"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent">
   
 <TextView 
     android:layout_width="fill_parent"
     android:layout_height="wrap_content"
     android:text="@string/hello"/>
    
 <com.dearpeople.android.test.ani.StarTwinkleImageView
  android:layout_width="wrap_content"
  android:layout_height="wrap_content"
  android:layout_gravity="center_horizontal"/>

</LinearLayout>


StarAniActivity.java
package com.dearpeople.android.test.ani;
import android.app.*;
import android.graphics.drawable.*;
import android.os.*;

public class StarAniActivity extends Activity {

   @Override
   public void onCreate(Bundle savedInstanceState) {
       super.onCreate(savedInstanceState);
       setContentView(R.layout.main);
   }
}

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.