Android中的动画2(逐帧动画)
程序员文章站
2024-03-24 12:42:10
...
逐帧动画就比较简单了,就是一帧一帧的播放动画,每一帧都是有我们来定义的。
在res/drawable文件夹下新建一个Root element为animation-list的xml文件,命名为animation
res/drawable/animation.xml
<?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/lu"
android:duration="200" />
<item
android:drawable="@drawable/panda"
android:duration="200" />
<item
android:drawable="@drawable/taiger"
android:duration="200" />
<!--
一个item代表一帧
android:drawable 表示这一帧所显示的图片
android:duration 表示这一帧的持续时间
-->
</animation-list>
然后在activity布局中声明一个ImageVIew,并且该ImageVIew用src引用animation.xml
activity_main.xml:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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"
android:orientation="vertical"
tools:context="com.demo.ln.exam.MainActivity">
<ImageView
android:id="@+id/image"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:src="@drawable/animation" />
</RelativeLayout>
在MainActivity中获取AnimationDrawable实例,用该实例启动动画:
MainActivity.java
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
ImageView imageView;
AnimationDrawable animationDrawable;
@TargetApi(Build.VERSION_CODES.KITKAT)
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
imageView = (ImageView) findViewById(R.id.image);
//获取AnimationDrawable的实例
animationDrawable = (AnimationDrawable) imageView.getDrawable();
//启动动画
animationDrawable.start();
imageView.setOnClickListener(this);
}
@Override
public void onClick(View v) {
//暂停动画
animationDrawable.stop();
}
}
lu.png
panda.png
taiger.png
到这里逐帧动画就完结了,比较简单。