我正在尝试在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;
}
}
}
});
答案 0 :(得分:1)
我发现了错误。似乎每次循环时我都必须重新实例化LayoutParams
,在使用相同的LayoutParams
实例时仅设置边距属性是不够的。我认为它会在调用addView()
方法后立即将按钮添加到指定的布局,但它实际上是在最后执行它(当方法完成时),因为它将所有按钮放在同一个(最后一个)坐标。
代码:
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();
}
});