0

I want myImageView to locate itself somewhere on a random position inside the screen, without pushing textviews away. I found this code in another thread, but I can't get it to work.

 myImageView = (ImageView) findViewById(R.id.myImageView);
        LinearLayout game = (LinearLayout)findViewById(R.id.game);

        int width = game.getWidth();
        int height = game.getHeight();

        random = new Random();

        int x = width;
        int y = height;

        int imageX = random.nextInt(x-50)+50;
        int imageY = random.nextInt(y-100)+100;

        myImageView.setX(imageX);
        myImageView.setY(imageY);

2 Answers2

0

You can give margin programmatically between certain range, may be you can use device width or height for range. Check this links for setting margin dynamically on run time and get screen dimension.

Community
  • 1
  • 1
Bills
  • 768
  • 7
  • 19
  • Looks helpful, but please put the relevant parts to your answer. For now this is a link only answer. – rekire Apr 26 '16 at 20:24
0

I Think first get programmatically device size then set image view width & height

WindowManager wm = (WindowManager)context.getSystemService(Context.WINDOW_SERVICE);
Display display = wm.getDefaultDisplay();

Display display = getWindowManager().getDefaultDisplay(); 
int width = display.getWidth();  // deprecated
int height = display.getHeight();  // deprecated

hear you get width & height now set image view size

android.view.ViewGroup.LayoutParams layoutParams =myImageView.getLayoutParams();
layoutParams.width = 30;
layoutParams.height = 30;
myImageView.setLayoutParams(layoutParams);

and if you still have a problem to change it's size try to put it inside of a LinearLayout and manipulate the imageView size using the layout params:

LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(30, 30);
myImageView.setLayoutParams(layoutParams);
Hardik Parmar
  • 712
  • 2
  • 13
  • 28