If you think the Android project cube-sdk listed in this page is inappropriate, such as containing malicious code/tools or violating the copyright, please email info at java2s dot com, thanks.
Java Source Code
package in.srain.cube.views.mix;
//fromwww.java2s.comimport android.os.Handler;
import android.os.Looper;
/**
* A player who can play a @Playable object. It can play next till end and play previous till head.
* <p/>
* Once it go to the last element, it can play by the reverse order or jump to the first and play again.
* <p/>
* Between each frame, there is a pause, you can call `setTimeInterval()` to set the time interval you want.
*
* @author huqiu.lhq
*/publicclass AutoPlayer {
/**
* Define how an object can be auto-playable.
*/publicinterface Playable {
publicvoid playTo(int to);
publicvoid playNext();
publicvoid playPrevious();
publicint getTotal();
publicint getCurrent();
}
publicenum PlayDirection {
to_left, to_right
}
publicenum PlayRecycleMode {
repeat_from_start, play_back
}
private PlayDirection mDirection = PlayDirection.to_right;
private PlayRecycleMode mPlayRecycleMode = PlayRecycleMode.repeat_from_start;
privateint mTimeInterval = 5000;
private Playable mPlayable;
private Runnable mTimerTask;
privateboolean mSkipNext = false;
privateint mTotal;
privateboolean mPlaying = false;
public AutoPlayer(Playable playable) {
mPlayable = playable;
}
publicvoid play() {
play(0, PlayDirection.to_right);
}
publicvoid skipNext() {
mSkipNext = true;
}
publicvoid play(int start, PlayDirection direction) {
if (mPlaying)
return;
mTotal = mPlayable.getTotal();
if (mTotal <= 1) {
return;
}
mPlaying = true;
playTo(start);
final Handler handler = new Handler(Looper.myLooper());
mTimerTask = new Runnable() {
@Override
publicvoid run() {
playNextFrame();
if (mPlaying) {
handler.postDelayed(mTimerTask, mTimeInterval);
}
}
};
handler.postDelayed(mTimerTask, mTimeInterval);
}
publicvoid play(int start) {
play(start, PlayDirection.to_right);
}
publicvoid stop() {
if (!mPlaying) {
return;
}
mPlaying = false;
}
public AutoPlayer setTimeInterval(int timeInterval) {
mTimeInterval = timeInterval;
returnthis;
}
public AutoPlayer setPlayRecycleMode(PlayRecycleMode playRecycleMode) {
mPlayRecycleMode = playRecycleMode;
returnthis;
}
privatevoid playNextFrame() {
if (mSkipNext) {
mSkipNext = false;
return;
}
int current = mPlayable.getCurrent();
if (mDirection == PlayDirection.to_right) {
if (current == mTotal - 1) {
if (mPlayRecycleMode == PlayRecycleMode.play_back) {
mDirection = PlayDirection.to_left;
playNextFrame();
} else {
playTo(0);
}
} else {
playNext();
}
} else {
if (current == 0) {
if (mPlayRecycleMode == PlayRecycleMode.play_back) {
mDirection = PlayDirection.to_right;
playNextFrame();
} else {
playTo(mTotal - 1);
}
} else {
playPrevious();
}
}
}
privatevoid playTo(int to) {
mPlayable.playTo(to);
}
privatevoid playNext() {
mPlayable.playNext();
}
privatevoid playPrevious() {
mPlayable.playPrevious();
}
}