我正在制作一个程序,在同一个ImageView中显示图像的不同部分。但它应该在任何两个图像变化之间等待一段时间,大约500毫秒。 像这样:
for(int i=1; i<=4;i++){
for(int j=1;j<=4;j++){
//code to refresh the image.
// wait for 500 milliseconds before resuming the normal iteration
}
}
我尝试使用以下代码:
for(int i=1; i<=4;i++){
for(int j=1;j<=4;j++){
//code to refresh the image.
Thread.sleep(500);
}
}
但这只显示图像的最后一段,而不是逐段显示。顺便说一句,每个片段保存为pic1,pic2,pic3 ..等等(它们都是不同的图像)。我想要一个解决方案,按以下顺序显示它们:
非常感谢
答案 0 :(得分:3)
如果这是在你的UI线程循环中,你应该使用AsyncTask
或Timer
来实现你的目标,以避免阻止UI。
使用AsyncTask
:
class UpdateImages extends AsyncTask<Void, Integer, Boolean> {
@Override
protected void onPreExecute() {
}
@Override
protected void onProgressUpdate(Integer... values) {
// refresh the image here
}
@Override
protected Boolean doInBackground(Void... params) {
for(int i=0; i<4; i++) {
for(int j=0; j<4; j++) {
// NOTE: Cannot call UI methods directly here.
// Call them from onProgressUpdate.
publishProgress(i, j);
try {
Thread.sleep(500);
} catch(InterruptedException) {
return false;
}
}
}
return true;
}
@Override
protected void onPostExecute(Boolean result) {
}
}
然后打电话
new UpdateImages().execute();
当您想要开始此任务时。以这种方式使用AsyncTask
可以避免阻止您的用户界面,并且仍然可以让您按计划进行任何操作。