Reputation: 1489
I am trying to place several buttons dynamically in RelativeLayout
. The problem is that all the buttons are placed at the same spot even thought the x and y coordinates are calculated properly. Is it the right way to specify coordinates using LayoutParams
and setting marginRight
, marginBottom
?
Code:
layout.getViewTreeObserver().addOnGlobalLayoutListener(new OnGlobalLayoutListener()
{
@Override
public void onGlobalLayout()
{
layout.getViewTreeObserver().removeGlobalOnLayoutListener(this);
RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(BUTTON_WIDTH, BUTTON_HEIGHT);
int currentX = 20;
int currentY = 20;
for (Product product: controller.getProducts("pizza")){
Log.d(TAG, "CurrentY: " + currentY);
Log.d(TAG, "CurrentX: " + currentX);
Button tempButton = new Button(getActivity());
tempButton.setId(product.getId());
tempButton.setText(product.getName());
layoutParams.rightMargin = currentX;
layoutParams.bottomMargin = currentY;
tempButton.setLayoutParams(layoutParams);
layout.addView(tempButton);
if (layout.getWidth() < currentX + MARGIN_LEFT + BUTTON_WIDTH){
currentX = 20;
currentY += BUTTON_HEIGHT + MARGIN_BOTTOM;
}
else{
currentX += MARGIN_LEFT + BUTTON_WIDTH;
}
}
}
});
Upvotes: 1
Views: 2719
Reputation: 1489
I have found the error. It seems like that I have to re-instantiate LayoutParams
each time it goes through the loop, it is not enough to just set margin attributes while using the same LayoutParams
instance. I thought that it adds the button to the specified layout immediately after addView()
method is called, but it actually does it at the end (When the method is finished), because it placed all the buttons to the same (last) coordinates.
Code:
layout.getViewTreeObserver().addOnGlobalLayoutListener(new OnGlobalLayoutListener()
{
@Override
public void onGlobalLayout()
{
layout.getViewTreeObserver().removeGlobalOnLayoutListener(this);
RelativeLayout.LayoutParams layoutParams;
int currentX = 20;
int currentY = 20;
for (Product product: controller.getProducts("pizza")){
layoutParams = new RelativeLayout.LayoutParams(BUTTON_WIDTH, BUTTON_HEIGHT);
Button tempButton = new Button(getActivity().getApplicationContext());
tempButton.setId(product.getId());
tempButton.setText(product.getName());
layoutParams.setMargins(currentX, currentY, 0, 0);
tempButton.setLayoutParams(layoutParams);
layout.addView(tempButton);
if (layout.getWidth() < currentX + MARGIN_LEFT + (2 * BUTTON_WIDTH)){
currentX = 20;
currentY += BUTTON_HEIGHT + MARGIN_BOTTOM;
}
else{
currentX += MARGIN_LEFT + BUTTON_WIDTH;
}
}
//layout.requestLayout();
}
});
Upvotes: 1