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

songoku1610
  • 1,576
  • 1
  • 13
  • 17

2 Answers2

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)

sachithkn
  • 457
  • 1
  • 4
  • 13
  • You're right, this is cause of problem, Do you know how to set position of ImageView instead use setMargins? – songoku1610 Jul 01 '15 at 08:39
  • try this http://stackoverflow.com/questions/6535648/how-can-i-dynamically-set-the-position-of-view-in-android.Or else try to set padding for layout layout.setPadding(0,padding,0,0); It will have same effect as margin. – sachithkn Jul 01 '15 at 09:14
  • I used setX(), setY() and this is result: http://i.stack.imgur.com/IzEcW.png. It always have a large space from left and top screen. I don't know why? – songoku1610 Jul 01 '15 at 09:46
  • may be that margin is from layout ,have a look – sachithkn Jul 01 '15 at 15:51
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.

Taha
  • 531
  • 4
  • 21