simplify
simplify

Reputation: 109

place images inside a layout android

I want to place some images (triggered on click action) inside a layout. I have to place them such that they don't get out of the parent layout.

Code I'm using to add a new image on clicking the layout:

LinearLayout layout = (LinearLayout) findViewById(R.id.layout);
    ImageView image = new ImageView(this);
LinearLayout.LayoutParams coordinates = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
image.setLayoutParams(coordinates);
image.setImageResource(R.drawable.image);
layout.addView(image);

If I press on the layout , I must see my imageView put randomly.

Random random = new Random();
int x = random.nextInt(layout.getWidth());
int y = random.nextInt(layout.getHeight());
image.setX(x);
image.setY(y);

But this won't do it. And I see those images outside my layout too.

Upvotes: 0

Views: 58

Answers (1)

nomag
nomag

Reputation: 300

You are setting x & y which are upper left-top corner - starting point of image to display it. As x/y value can be right/bottom corner, therefore, your image goes out of layout in that case. Please note - x, y are starting point from where your image will be drawn. You need to make sure that layoutWidth - x >= imageWidth and layoutHeight - y >= imageHeight.

Upvotes: 1

Related Questions