Java 实时更新onTouchEvent中的ImageView

Java 实时更新onTouchEvent中的ImageView,java,android,Java,Android,在扩展活动的类中的onTouchEvent方法中,我有一些逐个更改的ImageView,这是通过在执行下一个更改之前等待一点来完成的 //in the onTouchEvent method //ivList is an arrayList of imageViews ivList.get(0).setImageResource(R.drawable.drawable1); synchronized (this) { try { wait(500); } catc

在扩展活动的类中的onTouchEvent方法中,我有一些逐个更改的ImageView,这是通过在执行下一个更改之前等待一点来完成的

//in the onTouchEvent method
//ivList is an arrayList of imageViews
ivList.get(0).setImageResource(R.drawable.drawable1);
synchronized (this) {
    try {
        wait(500);
    } catch (InterruptedException e) {
    }
}
ivList.get(1).setImageResource(R.drawable.drawable2);

但是,当执行此操作时,更改仅在onTouchEvent结束后发生,因此结果是一个小延迟,然后两个imageView同时更改,而不是一个imageView更改,一个小延迟,然后第二个更改。有人能解释一下如何解决这个问题吗?

问题是你不应该使用wait,因为它会阻塞主线程

ivList.get(0).setImageResource(R.drawable.drawable1); // this is doing in main thread
synchronized (this) {
    try {
        wait(500); // this blocks the main thread
    } catch (InterruptedException e) {
    }
}
ivList.get(1).setImageResource(R.drawable.drawable2); // this is also doing in main thread
试着跟随

Runnable r = new Runnable() {
    @Override
    public void run() {
        ivList.get(1).setImageResource(R.drawable.drawable2);
    }
};
ivList.get(0).setImageResource(R.drawable.drawable1);
// no synchronized is needed
new Handler().postDelayed(r,500); // call to change the image after 500s
当然,您的Runnable和Handler可以在其他位置创建它们,这样您就不必在每次触发onTouchEvent时都创建它们

好的,如果你想让它对10张图片有效

// these are local variables
//create a contant int array for the 10 images
int[] imgs = {R.drawable.drawable1 , R.drawable.drawable2 ,....,R.drawable.drawable10};
int count = 0; // counting which image should show
// local variable ends

// initialize
Handler handler = new Handler();
Runnable r = new Runnable() {
        @Override
        public void run() {
            if (count < 9){
                count++;
                ivList.get(count).setImageResource(imgs[count]);
                handler().postDelayed(r,500);
            }
        }
    };

// in your touch event

ivList.get(0).setImageResource(R.drawable.drawable1);
// no synchronized is needed
handler().postDelayed(r,500); // call to change the image after 500s

wait方法具体采用哪些参数?参数为long timeout。500? 您希望延迟多长时间…它以毫秒为参数,因此500对于人眼来说几乎是瞬间的。你只是想阻止线程锁定吗?参数是不相关的。即使我把它设为1000秒,问题仍然存在。ImageView只有在onTouchEvent返回true后才会更新,而不是立即更新。你是说你不能看到R.drawable.drawable1,但只能看到R.drawable.drawable2吗?如果我想用10个ImageView执行此操作,我会怎么做?你是说10个图像的1对1?是的,我每次都必须创建单独的Runnable吗?