0

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.

asked Nov 5, 2020 at 15:30

1 Answer 1

1
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)

answered Nov 5, 2020 at 15:39
Sign up to request clarification or add additional context in comments.

1 Comment

Okay this works, I am trying to understand why but thanks alot!

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.