我有这段代码:
public void createTask() {
for (int i = 0; i < 6; i++) {
Random rnd = new Random();
int color = rnd.nextInt(10);
showImage(color);
}
但我希望它循环浏览图像视图..所以显示一个,将其保持在屏幕上3秒钟,然后显示第2个,在屏幕上保持3秒,显示第3个等等。
我已经制作了showImage和hideImage方法来保持代码清洁:
public void showImage(int color) {
((ImageView) findViewById(myImagebtns[color]))
.setVisibility(View.VISIBLE);
};
我应该如何编程等待时间(睡眠?线程?)而不是锁定UI?
答案 0 :(得分:2)
要阻止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
都是您应用的费用。)
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