Drawable Animation是逐帧动画,那么使用它之前必须先定义好各个帧。我们可以通过代码定义,也可以使用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/icon_aboutus" android:duration="200" /> <item android:drawable="@drawable/icon_join_menu" android:duration="200" /> <item android:drawable="@drawable/icon_join_opinion" android:duration="200" /> </animation-list>
其中android:oneshot=“true”表示该动画只播放一次,等于false时则循环播放。<item/>标签定义各个帧显示的图片。显示顺序依照<item/>定义顺序。
再看主界面的activity:
public class MainActivity extends Activity { public ImageView iv_start; public ImageView iv_stop; public ImageView iv_animation; public AnimationDrawable drawableAnimation; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); iv_start = (ImageView) findViewById(R.id.iv_start); iv_stop = (ImageView) findViewById(R.id.iv_stop); iv_animation = (ImageView) findViewById(R.id.iv_animation); iv_start.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { startAnimation(); } }); iv_stop.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { stopAnimation(); } }); iv_animation.setBackgroundResource(R.drawable.animations); drawableAnimation = (AnimationDrawable) iv_animation.getBackground(); } public void startAnimation(){ drawableAnimation.start(); } public void stopAnimation(){ drawableAnimation.stop(); } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.main, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { int id = item.getItemId(); if (id == R.id.action_settings) { return true; } return super.onOptionsItemSelected(item); } }
时间: 2024-11-03 21:58:45