Place the image at random x,y of the screen and make the image invisible after certain peroid in android
I need to create an image at random places. After few seconds it has to be disappeared. After the first image get disappeared the second image has to come. I used the following code to place the image at random coordinates and use a handler to make it invisible after few seconds. I used for loop to create some number of images. All the images comes and goes at the same time. I think the for loop is the problem. I couldn't find a solution for that. Any help is appreciated.
ImageView iv=null;
RelativeLayout rl=null;
Random rand= new Random();
int min=10, max=100;
int randomNum;
@Overr开发者_StackOverflowide
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
rl = (RelativeLayout) findViewById(R.id.my_relative_layout);
for(int i=0;i<100;i++){
randomNum = rand.nextInt(max - min + 1) + min;
Log.d("RandomNum",Integer.toString(randomNum));
Log.d("i value",Integer.toString(i));
iv = new ImageView(this);
iv.setBackgroundColor(Color.YELLOW);
RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(30, 40);
params.leftMargin = 50+randomNum;
params.topMargin = 60+randomNum;
rl.addView(iv, params);
timerDelayRemoveView(500, iv);
}
}
public void timerDelayRemoveView(long time, final ImageView iv){
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
public void run() {
iv.setVisibility(View.GONE);
}
}, time);
}
You can try to implement a timerDelayAddView
(like you delayed timerDelayRemoveView
) where you specify an image-dependent delay (e.g. 2000 * i
) before you call addView
.
精彩评论