1

我正在尝试将几个按钮动态放置在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;
                    }


                }

            }
        });
4

1 回答 1

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();

        }
    });
于 2013-10-17T10:31:26.290 回答