AnimationView 继承View
public class AnimationView extends View {
Bitmap[] bitmap; //图片的数组
int sleepTime = 1000;
public boolean isRunning = true;
int currentImageIndex = 0;
int viewWidth, viewHeight;
Thread thread;
public AnimationView(Context context, AttributeSet attrs) {
super(context, attrs);
//读取自定义属性 typedArray 封装了子控件的属性
//attrs布局文件中定义的所有属性
TypedArray typedArray=context.obtainStyledAttributes(attrs, R.styleable.AnimationView);
float defValue=1000;
sleepTime=(int) typedArray.getFloat(R.styleable.AnimationView_sleep_time, defValue);
//读取数组
Resources resources=context.getResources();
//获取数组
TypedArray taImage=resources.obtainTypedArray(R.array.animationImages);
int length=taImage.length();
bitmap = new Bitmap[length];
for (int i=0;i<length;i++)
{
//读取图的id
int imageId=taImage.getResourceId(i, 0);
Bitmap image=BitmapFactory.decodeResource(resources, imageId);
bitmap[i]=image;
Log.i("测量", "image:"+image.getWidth()+","+image.getHeight());
}
MyRunnable myRunnable = new MyRunnable();
thread = new Thread(myRunnable);
thread.start();
}
//测量控件大小,设置控件大小
//不测量,控件大小是父容器的大小,别的控件不显示
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
//控件大小是图的大小.
int imageWidth=bitmap[0].getWidth();
int imageHeight=bitmap[0].getHeight();
setMeasuredDimension(imageWidth, imageHeight);
}
@Override
protected void onDraw(Canvas canvas) {
Bitmap drawImage = bitmap[currentImageIndex];
int x = (viewWidth - drawImage.getWidth()) / 2;
int y = (viewHeight - drawImage.getHeight()) / 2;
Paint paint = new Paint();
canvas.drawBitmap(drawImage, x, y, paint);
Log.i("animationView", "onDraw x=" + x);
}
@Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
// TODO Auto-generated method stub
super.onSizeChanged(w, h, oldw, oldh);
viewHeight = h;
viewWidth = w;
}
class MyRunnable implements Runnable {
@Override
public void run() {
while (isRunning) {
try {
currentImageIndex++;
if (currentImageIndex >= bitmap.length) {
currentImageIndex = 0;
}
// 工作线程中更新界面调postInvalidate();
// 主线程中更新界面调invalidate();
postInvalidate();
// invalidate();
Log.i("animationView", "currentImageIndex="+ currentImageIndex);
Thread.currentThread().sleep(sleepTime);
} catch (Exception e) {
// TODO: handle exception
}
}
}
}
}
二 资源文件 res—>values—>attrs.xml
<declare-styleable name="AnimationView">
<attr name="sleep_time" format="float"></attr>
<attr name="images" format="reference"></attr>
</declare-styleable>
三,布局文件 layout
<com.ttttttt.all.widget.AnimationView
android:id="@+id/animationView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
AnimationView:images="@array/animationImages"
AnimationView:sleep_time="100" />