要不阻塞 UI 线程,请使用Handler
其postDelayed
方法。
int repeatCount = 0;
handler = new Handler();
runnable = new Runnable() {
@Override
public void run() {
switchImage();
Log.d("MSG", "repeatCount is : " + repeatCount);
repeatCount ++;
if(repeatCount < 5) {
handler.postDelayed(this, 3000);
}
}
};
handler.postDelayed(runnable, 3000);
我建议您使用单个 ImageView 并每 3 秒切换一次其背景颜色或图像资源。(对每张图像使用ImageView
s 将是您的应用程序的成本。)
public void switchImage() {
ImageView myImageView = (ImageView) findViewById(R.id.myImageView);
// TODO: get your image or color here and apply it to your single imageView
// You may need an index while getting the next image or randomly get it.
myImageView.setImageResource(getNextImageResId());
}
编辑:如果您想切换 n 次,您可以定义一个变量(例如 repeatCount)并增加该变量。如果您注销,您会看到类似这样的内容(如您所见,每行有 3 秒的差异):
11-11 20:17:19.909: D/MSG(1068): repeatCount is : 0
11-11 20:17:22.917: D/MSG(1068): repeatCount is : 1
11-11 20:17:25.921: D/MSG(1068): repeatCount is : 2
11-11 20:17:28.921: D/MSG(1068): repeatCount is : 3
11-11 20:17:31.925: D/MSG(1068): repeatCount is : 4