格式化

廣告

廣告2

2012年8月21日 星期二

[Android程式範例] 程式載入等待畫面動畫美化

Android程式教學-程式載入等待畫面
Android載入畫面教學
另外新增一個java類別-LodingView


package wht.android.loading;

import android.content.Context;
import android.graphics.Canvas;
import android.util.AttributeSet;
import android.widget.ImageView;

public class LoadingView extends ImageView implements Runnable
{
 private boolean isStop = false;
 
 private int[] imageIds;
 private int index = 0;
 private int length = 1;
 
 public LoadingView(Context context)
 {
  this(context, null);
 }

 public LoadingView(Context context, AttributeSet attrs)
 {
  super(context, attrs);
 }
 
 public void setImageIds(int[] imageId)
 {
  this.imageIds = imageId;
  if(imageIds != null && imageIds.length > 0)
  {
   length = imageIds.length;
  }
 }
 
  @Override
 protected void onDetachedFromWindow()
 {
  // TODO Auto-generated method stub
  super.onDetachedFromWindow();
  isStop = true;
 }

 @Override
 protected void onDraw(Canvas canvas)
 {
  // TODO Auto-generated method stub
  super.onDraw(canvas);
  if(imageIds != null && imageIds.length > 0)
  {
   this.setImageResource(imageIds[index]);
  }
 }

 public void run()
 {
  while(!isStop)
  {
   index = ++index % length;
   postInvalidate();
   try
   {
    Thread.sleep(400);
   }
   catch (InterruptedException e)
   {
    e.printStackTrace();
   }
  }
 }
 
 public void startAnim()
 {
  new Thread(this).start();
 }
 
 public void initLoadingImages()
    {
        int[] imageIds = new int[6];
        imageIds[0] = R.drawable.loader_frame_1;
        imageIds[1] = R.drawable.loader_frame_2;
        imageIds[2] = R.drawable.loader_frame_3;
        imageIds[3] = R.drawable.loader_frame_4;
        imageIds[4] = R.drawable.loader_frame_5;
        imageIds[5] = R.drawable.loader_frame_6;
        
        this.setImageIds(imageIds);
    }


}


主程式:
package wht.android.loading;
import android.app.Activity;
import android.os.Bundle;

public class MainActivity extends Activity
{
    private LoadingView main_imageview;
    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.loding_page);
        main_imageview = (LoadingView)findViewById(R.id.main_imageview);
        main_imageview.initLoadingImages();
        new Thread()
        {
            @Override
            public void run()
            {
                main_imageview.startAnim();
            }
        }.start();
        //setContentView(R.layout.main);
    }
}