gpt4 book ai didi

android - 将按钮动态放置在 RelativeLayout 中的特定位置

转载 作者:行者123 更新时间:2023-11-30 03:19:32 25 4
gpt4 key购买 nike

我试图在 RelativeLayout 中动态放置几个按钮。问题是所有按钮都放在同一个位置,即使 x 和 y 坐标计算正确。使用 LayoutParams 并设置 marginRightmarginBottom 来指定坐标是否正确?

代码:

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


}

}
});

最佳答案

我发现了错误。似乎每次循环时我都必须重新实例化 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();

}
});

关于android - 将按钮动态放置在 RelativeLayout 中的特定位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19414492/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com