我正在尝试将几个按钮动态放置在RelativeLayout
. 问题是所有按钮都放在同一个位置,即使 x 和 y 坐标计算正确。LayoutParams
使用和设置指定marginRight
坐标是否正确marginBottom
?
代码:
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;
}
}
}
});