这一节比较简单,在androidAPI里有详细的讲解,大家可以看下,我就直接上代码了
一: 布局
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity"
android:orientation="vertical" >
<ImageView
android:layout_gravity="center_horizontal"
android:id="@+id/iv_zhangxin"
android:layout_width="150dp"
android:layout_height="150dp"
/>
<Button
android:id="@+id/bt_begin"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="开始" />
<Button
android:id="@+id/bt_stop"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="停止" />
</LinearLayout>
二:资源
资源在新建的drawable文件夹中
<?xml version="1.0" encoding="utf-8"?>
<animation-list xmlns:android="http://schemas.android.com/apk/res/android"
android:oneshot="false" >
<item
android:drawable="@drawable/image_one"
android:duration="200"/>
<item
android:drawable="@drawable/image_two"
android:duration="200"/>
<item
android:drawable="@drawable/image_three"
android:duration="200"/>
<item
android:drawable="@drawable/image_four"
android:duration="200"/>
<item
android:drawable="@drawable/image_five"
android:duration="200"/>
</animation-list>
三:代码
package com.example.bujiandonghua;
import android.app.Activity;
import android.graphics.drawable.AnimationDrawable;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.DrawableContainer;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
//1,什么事动画
public class MainActivity extends Activity implements OnClickListener{
private ImageView iv_zhangxin;
private AnimationDrawable ad_zhangxin;
private Button bt_begin;
private Button bt_stop;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
iv_zhangxin = (ImageView) findViewById(R.id.iv_zhangxin);
iv_zhangxin.setBackgroundResource(R.drawable.my_animation);
//getBackground()返回的是drawable,而AnimationDrawable 继承 DrawableContainer
//DrawableContainer extends Drawable
ad_zhangxin = (AnimationDrawable) iv_zhangxin.getBackground();**
bt_begin = (Button) findViewById(R.id.bt_begin);
bt_stop = (Button) findViewById(R.id.bt_stop);
bt_begin.setOnClickListener(this);
bt_stop.setOnClickListener(this);
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.bt_begin:
ad_zhangxin.start();
System.out.println("动起来");
break;
case R.id.bt_stop:
ad_zhangxin.stop();
break;
default:
break;
}
}
}
注意:在onCreate()方法里面,不能执行AnimationDrawable的onStart()的方法。因为AnimationDrawable没有依附在我们的Window上。没有添加到window上。那怎么开机启动动画呢?请继续阅读下一张!再见。