Java 循环浏览imageview

Java 循环浏览imageview,java,android,multithreading,sleep,wait,Java,Android,Multithreading,Sleep,Wait,我有这个密码: public void createTask() { for (int i = 0; i < 6; i++) { Random rnd = new Random(); int color = rnd.nextInt(10); showImage(color); } 如何编程等待时间(sleep?thread?)而不锁定UI?要不阻止UI线程,请使用处理程序及其postDelayed方法 int re

我有这个密码:

    public void createTask() {

    for (int i = 0; i < 6; i++) {
        Random rnd = new Random();
        int color = rnd.nextInt(10);
        showImage(color);
    }

如何编程等待时间(sleep?thread?)而不锁定UI?

要不阻止UI线程,请使用
处理程序及其
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);
编辑:如果要切换n次,可以定义一个变量(如repeatCount)并递增该变量。如果您注销,您将看到类似的情况(因为您看到每行有3秒的差异):


为什么不只使用一个ImageView并更改其颜色?这要简单得多。public void showImage(int-color){imageview.setBackgroundColor(color);}确定。实现了您的方法。我想,如果我想切换5次,我会这样调用这个方法吗?对于(int i=0;iNo这将导致5个无限循环。请根据您的需要查看我编辑的答案。我知道,但您的解决方案会同时引发5个实例?因此在第3个和第4个之间不会有3秒延迟?我猜您的问题已经得到了回答?谢谢aegaen。不完全正确。我如何暂停onCreate线程以等待显示的第5个图像,然后再重新启动爱你吗?
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);
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());
}
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