帧动画(Frame Animation,又叫Drawable Animation)是最简单的Android动画效果,其模仿的是电影的多重连续帧播放策略,通过视觉残留来让人感知到动画效果。
帧动画将一张张Drawable按顺序排列,并逐张按时播放来实现动画效果,其对应的Android类是AnimationDrawable,
帧动画有两种实现方式:纯代码实现和XML实现,XML实现相对更简单。
1.xml写法:第一步定义xml
将动画XML文件定义在 res/drawable/
目录下,其中的条目是每一帧的顺序和展示时间。XML文件的根元素是<animation-list>节点,其子元素是一个个的<item>节点,每一个item节点定义一个帧,每个帧中包含其需要展示的Drawable以及其展示时间。用法如下:
res/drawable/frame_animation_demo.xml定义
<animation-list xmlns:android="http://schemas.android.com/apk/res/android">
<item
android:drawable="@drawable/le"
android:duration="100"/>
<item
android:drawable="@drawable/anita"
android:duration="100"/>
</animation-list>
2.xml写法:第二步布局:
<LinearLayout
android:orientation="vertical"
xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent"
android:layout_height="match_parent">
<Button
android:id="@+id/start_frame"
android:text="播放帧动画"
android:textSize="25dp"
android:layout_marginTop="10dp"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"/>
<Button
android:id="@+id/close_stop"
android:text="暂停帧动画"
android:textSize="25dp"
android:layout_marginTop="10dp"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"/>
<TextView
android:id="@+id/show_frame"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="8"/>
</LinearLayout>
3.xml写法:第三步java代码:
@ContentView(R.layout.fragment1)
public class Fragment1 extends Fragment {
//注解控件
@ViewInject(R.id.start_frame)
Button start_frame;
@ViewInject(R.id.close_stop)
Button close_stop;
@ViewInject(R.id.show_frame)
TextView show_frame;
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
//注解Fragment
return x.view().inject(this,inflater,container);
}
//注解定义点击事件(开启)
@Event(type = View.OnClickListener.class,value = R.id.start_frame)
private void getStart_frame(View view){
//为testview设置已经添加完成的animation_list背景模式:
show_frame.setBackgroundResource(R.drawable.start);
获取背景转换成动画模式:
AnimationDrawable drawable= (AnimationDrawable) show_frame.getBackground();
//开启动画:
drawable.start();
}
//注解定义点击事件(暂停)
@Event(type = View.OnClickListener.class,value = R.id.close_stop)
private void getClose_frame(View view){
show_frame.setBackgroundResource(R.drawable.start);
AnimationDrawable drawable= (AnimationDrawable) show_frame.getBackground();
//暂停动画:
drawable.stop();
}
}