您可以通過創建一個線程和一個處理程序,其中線程休眠一段時間,並在醒來時通過發送消息來通知處理程序,處理程序將在圖像視圖中更新圖像。
創建像下面4個領域:
private ImageView mImageView;
private Handler mImageChangingHandler;
private int mCurrentImageIndex = 0;
private BackgroundThread mImageUpdateThread;
在onCreate()
得到ImageView的,灑你的位圖,並將其添加到列表中,並創建一個處理程序,其更新ImageView的。在這裏你應該知道個人位圖數這是主位圖。像:
mImageView = (ImageView) findViewById(R.id.img);
Bitmap mainBitmap = BitmapFactory.decodeResource(getResources(), R.drawable.anim);
//number of individual bitmaps, which you should know.
final int numberOfImages = 21;
//individual bitmap width
int bitmapWidth = mainBitmap.getWidth()/numberOfImages;
//individual bitmap height
int bitmapHeight = mainBitmap.getHeight();
//list which holds individual bitmaps.
final List<Bitmap> animBitmaps = new ArrayList<>(numberOfImages);
//split your bitmap in to individual bitmaps
for (int index = 0; index < numberOfImages; index++) {
animBitmaps.add(Bitmap.createBitmap(mainBitmap, index * bitmapWidth, 0, bitmapWidth, bitmapHeight));
}
//set 1st bitmap to imageView.
mImageView.setImageBitmap(animBitmaps.get(mCurrentImageIndex));
mImageChangingHandler = new Handler(new Handler.Callback() {
@Override
public boolean handleMessage(Message msg) {
//increament current bitmap index
mCurrentImageIndex++;
//if current index is greater than the number of images, reset it to 0
if (mCurrentImageIndex > numberOfImages - 1) {
mCurrentImageIndex = 0;
}
mImageView.setImageBitmap(animBitmaps.get(mCurrentImageIndex));
return true;
}
});
//Create the background thread by passing the handler and start.
mImageUpdateThread = new BackgroundThread(mImageChangingHandler);
mImageUpdateThread.setRunning(true);
mImageUpdateThread.start();
,這將是你的BackgroundThread.class
:
public static class BackgroundThread extends Thread {
private Handler mHandler;
private boolean mRunning;
public BackgroundThread(Handler handler) {
mHandler = handler;
}
public void setRunning(boolean running) {
mRunning = running;
}
@Override
public void run() {
super.run();
while (mRunning) {
try {
//this sleeps for 100 milliseconds
sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
//send message to handler after sleep
mHandler.sendEmptyMessage(0);
}
}
}
}
終於在onDestroy()
停止線程。像:
mImageUpdateThread.setRunning(false);
boolean stopThread = true;
while (stopThread) {
try {
mImageUpdateThread.join();
//thread already stopped
stopThread = false;
} catch (InterruptedException e) {
e.printStackTrace();
}
}
mImageUpdateThread = null;
注:如果你想提高更新速度,減少線程睡眠時間。
TranslateAnimation? –
如何?翻譯動畫完成圖像視圖不是圖像內 –
檢查此:http://stackoverflow.com/questions/36894384/android-move-background-continuously-with-animation –