2017-09-14 67 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