( new AnimationDrawable().addFrame(getDrawable(R.drawable.a),200);)
代码
1.准备图片资源
将图片资源放在drawable-hdpi目录下
2.在drawable目录下新建animation-list类型文件
anim_frame.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/a" android:duration="100"/> <item android:drawable="@drawable/b" android:duration="100"/> <item android:drawable="@drawable/c" android:duration="100"/></animation-list>3.在布局文件中,添加
ImageView
,将其background
属性设置为动画资源xml<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="match_parent" android:layout_height="match_parent"> <Button android:id="@+id/btn_start" android:text="开始跳舞" android:textSize="25sp" android:layout_width="wrap_content" android:layout_height="wrap_content"/> <Button android:id="@+id/btn_stop" android:text="结束跳舞" android:textSize="25sp" android:layout_width="wrap_content" android:layout_height="wrap_content"/> <ImageView android:id="@+id/image" android:background="@drawable/anim_frame" android:layout_width="match_parent" android:layout_height="match_parent"/></LinearLayout>4.在java中,获取动画资源,调用
start( )
开启动画,stop( )
停止动画package com.lyp.frameanim;import android.graphics.drawable.AnimationDrawable;import android.graphics.drawable.Drawable;import android.support.v7.app.AppCompatActivity;import android.os.Bundle;import android.view.View;import android.widget.Button;import android.widget.ImageView;public class MainActivity extends AppCompatActivity implements View.OnClickListener{ private Button mBtnStart; private Button mBtnStop; private ImageView mImage; private AnimationDrawable mAnim; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main);// new AnimationDrawable().addFrame(getDrawable(R.drawable.a),200); initView(); mAnim = (AnimationDrawable) mImage.getBackground(); } private void initView() { mBtnStart= (Button) findViewById(R.id.btn_start); mBtnStop= (Button) findViewById(R.id.btn_stop); mImage= (ImageView) findViewById(R.id.image); mBtnStart.setOnClickListener(this); mBtnStop.setOnClickListener(this); } @Override public void onClick(View v) { switch (v.getId()){case R.id.btn_start:mAnim.start();break;case R.id.btn_stop:mAnim.stop();break; } }}总结