/**
* 實(shí)現(xiàn)類gif播放效果副编,可以伴以提示音
*
* @author felix.zhong
* @時(shí)間 2014-11-14下午5:39:45
*/
public class DynamicImage extends ImageView {
private int index = 0;
private MediaPlayer mediaPlayer = null;
// 繼續(xù)播放標(biāo)志
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();
}
// 設(shè)置循環(huán)播放標(biāo)志
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() {
// 設(shè)置圖片切換停止標(biāo)志
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>