在Android中,帧动画的本质是把一组预先准备好的图片循环切换播放,造成一种动画效果。
实现帧动画有两种方式,即
xml
和java
方法1:xml实现帧动画
第一步:导入帧动画素材
把准备的素材放到drawable目录
第三步:布局文件和Activity
布局文件:布局文件中添加两个点击按钮和一个图片控件
在
Activity
中添加启动&停止动画代码
public class MainActivity extends AppCompatActivity {
Button mButtonStart;
Button mButtonStop;
ImageView mImageViewShow;
AnimationDrawable mAnimationDrawable;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mImageViewShow = findViewById(R.id.image);
// 获取动画对象
mAnimationDrawable = (AnimationDrawable) mImageViewShow.getBackground();
mButtonStart = findViewById(R.id.button);
mButtonStart.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//开始动画
mAnimationDrawable.start();
}
});
mButtonStop = findViewById(R.id.button2);
mButtonStop.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//结束动画
mAnimationDrawable.stop();
}
});
}
}
方法2:用Java代码实现帧动画
Java代码实现帧动画跟xml很类似,只有Activity部分有点区别
public class MainActivity extends AppCompatActivity {
Button mButtonStart;
Button mButtonStop;
ImageView mImageViewShow;
AnimationDrawable mAnimationDrawable;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mImageViewShow = findViewById(R.id.image);
// 获取动画对象
mAnimationDrawable =new AnimationDrawable();
mAnimationDrawable.addFrame(getResources().getDrawable(R.drawable.img01),200);
mAnimationDrawable.addFrame(getResources().getDrawable(R.drawable.img02),200);
mAnimationDrawable.addFrame(getResources().getDrawable(R.drawable.img03),200);
mAnimationDrawable.addFrame(getResources().getDrawable(R.drawable.img04),200);
mAnimationDrawable.addFrame(getResources().getDrawable(R.drawable.img05),200);
mAnimationDrawable.addFrame(getResources().getDrawable(R.drawable.img06),200);
mAnimationDrawable.setOneShot(false);//设置循环播放
mImageViewShow.setBackground(mAnimationDrawable);
mButtonStart = findViewById(R.id.button);
mButtonStart.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//开始动画
mAnimationDrawable.start();
}
});
mButtonStop = findViewById(R.id.button2);
mButtonStop.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//结束动画
mAnimationDrawable.stop();
}
});
}
}
作者:huwei0814