0

I add ImageView to layout in runtime, But ImageView is smaller after every loop. This is my code:

 layout = (RelativeLayout)findViewById(R.id.layout_main); width = getWindowManager().getDefaultDisplay().getWidth(); height = getWindowManager().getDefaultDisplay().getHeight( for(int i=0; i< fruit.size();i++) { int id = getApplicationContext().getResources().getIdentifier(fruit.get(i).file, "drawable", getApplicationContext().getPackageName()); int h = random.nextInt(height); int w = random.nextInt(width); Logger.debug(TAG, "drawable/"+fruit.get(i).file+":"+id+":X="+w+":Y="+h); ImageView imageView =new ImageView(getApplicationContext()); imageView.setImageResource(id); imageView.setScaleX(0.3f); imageView.setScaleY(0.3f); RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT); layoutParams.setMargins(w,h,0,0); imageView.setLayoutParams(layoutParams); layout.addView(imageView); 

And this is my result: enter image description here

Please help me why and how to fix it? Thank you very much

More information: If I replace code

RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT); layoutParams.setMargins(w,h,0,0); imageView.setLayoutParams(layoutParams); 

By

imageView.setY(h); imageView.setX(w); 

Result will enter image description here

2 Answers 2

1

may be this create problem

layoutParams.setMargins(w,h,0,0); 

setmargin put margin as setMargins(int left, int top, int right, int bottom)

Sign up to request clarification or add additional context in comments.

4 Comments

You're right, this is cause of problem, Do you know how to set position of ImageView instead use setMargins?
try this stackoverflow.com/questions/6535648/… else try to set padding for layout layout.setPadding(0,padding,0,0); It will have same effect as margin.
I used setX(), setY() and this is result: i.sstatic.net/IzEcW.png. It always have a large space from left and top screen. I don't know why?
may be that margin is from layout ,have a look
0

I believe it's because of the Random class. You are already bounding the random number. You can shift the generated number, if you don't want it to approach to zero.

int h = random.nextInt(height) + height; 

Or you can change the seed if you are providing any. Please see the link below.

How the random numbers are calculated.

1 Comment

h and w only used for margin, if use your code, every object will fly out of screen

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.