2017-09-14 66 views
0

我想在布局中放置一些图像(在点击操作时触发)。我必须将它们放置成不会脱离父级布局。我使用上一下布局添加新的图像在布局中放置图像android

代码:

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); 

如果我按上的布局,我要看到我的ImageView放随机。

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

但是这不行。我也看到了我的布局外的那些图像。

+1

你在用什么“Random”? – mrid

+0

这是在点击动作,我想随机将图像放在我的布局,只要我点击布局。 – simplify

回答

1

您正在设置x & y这是左上角 - 图像的起点以显示它。由于x/y值可能是右下角,因此,在这种情况下,图像会脱离布局。 请注意 - x,y是您的图像绘制位置的起点。 您需要确保layoutWidth - x> = imageWidth和layoutHeight - y> = imageHeight。

+0

谢谢,这很好:) – simplify