public class MainActivity extends Activity {
boolean start=false;
ImageView img1=null;
AnimationDrawable ad=null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
img1=(ImageView)findViewById(R.id.img1);
ad=new AnimationDrawable();
for(int i=0;i<8;i++)
{
ad.addFrame(this.getResources().getDrawable(R.drawable.walk1+i), 50);
}
ad.setOneShot(true);
img1.setBackgroundDrawable(ad);
}
public void clickBtn(View view)
{
//获得背景动画对象
// AnimationDrawable ad=(AnimationDrawable)img1.getBackground();
if(!start)
{
ad.start();
start=true;
}else
{
ad.stop();
start=false;
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
frame.xml
<?xml version="1.0" encoding="utf-8"?>
<animation-list xmlns:android="http://schemas.android.com/apk/res/android" >
<item android:drawable="@drawable/walk1" android:duration="50" />
<item android:drawable="@drawable/walk2" android:duration="50" />
<item android:drawable="@drawable/walk3" android:duration="50" />
<item android:drawable="@drawable/walk4" android:duration="50" />
<item android:drawable="@drawable/walk5" android:duration="50" />
<item android:drawable="@drawable/walk6" android:duration="50" />
<item android:drawable="@drawable/walk7" android:duration="50" />
<item android:drawable="@drawable/walk8" android:duration="50" />
</animation-list>
main.xml
<LinearLayout 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=".MainActivity" >
<Button android:id="@+id/btn1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:onClick="clickBtn"
android:text="播放"
/>
<ImageView android:id="@+id/img1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
/>
</LinearLayout>