以下为本篇文章全部内容:
大家在网页中经常可以看懂动态图片,也就是gif格式的图片,在android中可以通过xml来定义这组动画,就是把多张有关联性的图片,放到了一起。并快速的切换下一张图片,就形成了动态图片,这个原理跟以前的电影胶卷类似,快速的更换图片达到一种连贯的效果,我们看起来就像是一组动作了。今天给大家带来的就是在android中如何使用xml来进行操作把一组图片做成一组动作。
效果图:

布局xml代码:
<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:paddingBottom="@dimen/activity_vertical_margin" android:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin" tools:context="com.example.xmlfram.MainActivity" > <ImageView android:id="@+id/iv" android:layout_width="match_parent" android:layout_height="match_parent" /> </RelativeLayout>
xml定义帧动画代码:
<?xml version="1.0" encoding="utf-8"?> <animation-list xmlns:android="http://schemas.android.com/apk/res/android" > <item android:drawable="@drawable/img_1" android:duration="200"/> <item android:drawable="@drawable/img_2" android:duration="200"/> <item android:drawable="@drawable/img_3" android:duration="200"/> <item android:drawable="@drawable/img_4" android:duration="200"/> <item android:drawable="@drawable/img_5" android:duration="200"/> <item android:drawable="@drawable/img_6" android:duration="200"/> <item android:drawable="@drawable/img_7" android:duration="200"/> <item android:drawable="@drawable/img_8" android:duration="200"/> </animation-list>
java实现代码:
public class MainActivity extends Activity {
private AnimationDrawable ss;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ImageView img = (ImageView)findViewById(R.id.iv);
img.setBackgroundResource(R.drawable.gif);
ss = (AnimationDrawable) img.getBackground();//获取AnimationDrawable对象
}
/*
* 触屏事件的时候开始动画
*/
public boolean onTouchEvent(MotionEvent event){
//判断事件是否为触屏事件
if(event.getAction()==MotionEvent.ACTION_DOWN){
ss.start();//AnimationDrawable的start方法开启动画
return true;
}
return super.onTouchEvent(event);
}
}如果大家有什么疑问可以加我QQ327388905进行学习交流
总赞数量:18274
总踩数量:128088
文章数量:29