Set Handler Postdelayed on Imageview dynamically

131 views Asked by At

I am creating like a Whack a Molee type of game, and I am creating imageviews at random positions on the screen.

The thing is, I am adding a postdelayed to a var I am creating every two seconds ( the var is the imageview) but it only acts to the last imageview created. It happens because every two seconds that var is replaced with a new instance of imageview.

How can I add an independent postdelayed or something that detects when 2 seconds has passed and removing that specific imageview.

Thanks!

 mv = new ImageView(this);

 new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                mv.setVisibility(View.GONE);
            }
        }, 2000);

I tried this, but only removes the very last imageview.

1

There are 1 answers

1
IntoVoid On
public void createImage() {
    final ImageView mv = new ImageView(this);
    // Do all your positioning and sizing (layout params) setting stuff here
    

    new Handler(getMainLooper()).postDelayed(new Runnable() {
        @Override
        public void run() {
            mv.setVisibility(View.GONE);
        }
    }, 2000);

}

Simply don't override the value every time, by using a local varaible inside a method. This way the mv instance will be the same in the runnable which is executed by the handler. (And also don't create a handler every time)

(You could also draw the entire thing on a canvas)