Android Why does this line of code execute after the for loop?

453 views Asked by At
  btnSwitch2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                btnSwitch2.setImageResource(R.drawable.on);
                myVib.vibrate(50);
                strobeFlash();
            }
        });

    }
 private void strobeFlash(){        
            for(int i=0; i<10;++i){
                turnOnFlash2();
                turnOffFlash2();
            }
    }

The code above executes when a button is pressed, I would like to change the picture of the image button. However, when the button is pressed, the for loop executes first then the line above it

btnSwitch2.setImageResource(R.drawable.on);

executes. Is there something I'm doing that's causing the loop to execute completely first?

1

There are 1 answers

2
Mohammad Arman On

Actually for loop execution is faster the then changing the image resource. You can add a postDelay() between the UI update and the for loop execution. It will solve the issue.

          btnSwitch2.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    btnSwitch2.setImageResource(R.drawable.on);
                    myVib.vibrate(50);
                    handler=new Handler();
                    Runnable r=new Runnable() {
                            public void run() {
                                strobeFlash();        

                            }
                    };
                    handler.postDelayed(r, 3000);

                }
            });

        }
        private void strobeFlash(){        
                for(int i=0; i<10;++i){
                    turnOnFlash2();
                    turnOffFlash2();
                }
        }