/**
* 实现类gif播放效果,可以伴以提示音
*
* @author felix.zhong
* @时间 2014-11-14下午5:39:45
*/
public class DynamicImage extends ImageView {
private int index = 0;
private MediaPlayer mediaPlayer = null;
// 继续播放标志
private boolean continuePlay = false;
private Handler handler;
public DynamicImage(Context context) {
super(context);
}
public DynamicImage(Context context, AttributeSet attrs) {
super(context, attrs);
}
/**
* 图片切换
*
* @author zhongcj
* @param resIds
* 资源图片id
* @param ms
* 毫秒值
*/
public void startRoation(final int resIds[], final long ms) {
if (continuePlay) {
// 如果正在播放,不做操作
return;
}
if (handler == null) {
handler = new Handler();
}
// 设置循环播放标志
continuePlay = true;
Runnable runnable = new Runnable() {
@Override
public void run() {
if (continuePlay) {
if (index == resIds.length) {
index = 0;
}
DynamicImage.this.setImageResource(resIds[index]);
index++;
handler.postDelayed(this, ms);
}
}
};
handler.post(runnable);
}
/**
* 图片切换并伴以声音提示
*
* @author zhongcj
* @param resIds
* @param ms
*/
public void startRoationWithTone(final int resIds[], final long ms) {
// 播放图片
startRoation(resIds, ms);
// 播放声音提示
playTone();
}
/**
* 停止切换
*/
public void stopRotation() {
// 设置图片切换停止标志
continuePlay = false;
// 如果声音正在播放,停之
if (mediaPlayer != null) {
if (mediaPlayer.isPlaying()) {
mediaPlayer.stop();
}
mediaPlayer.release();
}
}
/**
* 播放声音提示
*/
private void playTone() {
try {
if (mediaPlayer == null) {
mediaPlayer = new MediaPlayer();
} else {
mediaPlayer.reset();
}
Uri tone = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
mediaPlayer.setDataSource(getContext(), tone);
mediaPlayer.setLooping(false);
mediaPlayer.prepare();
mediaPlayer.start();
} catch (Exception e) {
Log.e("DynamicImage", "playTone error:\r\n" + e.getMessage());
}
}
}
public class MainActivity extends Activity {
private DynamicImage di;
private int[] imageIds;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
di = (DynamicImage) findViewById(R.id.di);
imageIds = new int[] { R.drawable.a, R.drawable.b, R.drawable.c,R.drawable.d, R.drawable.e, R.drawable.f };
di.startRoationWithTone(imageIds, 1550);
}
}
<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"
tools:context=".MainActivity" >
<com.demo.DynamicImage
android:id="@+id/di"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:src="@drawable/ic_launcher" />
</RelativeLayout>