1

我正在制作一个程序,在同一个 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.. 等等(它们都是不同的图像)。我想要一个按以下顺序显示它们的解决方案:

  • 图1
  • 等待 500 毫秒
  • 图2
  • 等待 500 毫秒
  • 图3
  • ... 等等

万分感谢

4

1 回答 1

3

如果这是在您的 UI 线程循环中,您应该使用 anAsyncTask或 aTimer来实现您的目标,以避免阻塞 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这种方式可以避免阻塞你的 UI,并且仍然可以让你按时做任何你想做的事情。

于 2012-10-21T05:53:38.390 回答