在RelativeLayout square中创建单元格

时间:2013-06-25 10:55:37

标签: android relativelayout

我在layout/activity.xml

中创建了RelativeLayout

我想通过以下方式以编程方式添加一些元素:

RelativeLayout rlayout = (RelativeLayout) findViewById(R.id.relativeLayout1); 
RelativeLayout.LayoutParams p = new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
 rlayout.addView(CustomView,p);

它有效,但添加的元素并不能填满所有视图,但我需要它。

并且我想在square(width = height)中添加这些元素,我该怎么做?

1 个答案:

答案 0 :(得分:0)

填写所有视图使用LayoutParams.MATCH_PARENT代替LayoutParams.WRAP_CONTENT。 要将布局设为正方形,只需创建int width,height = 300;然后:

RelativeLayout.LayoutParams p = new RelativeLayout.LayoutParams(width, height);

或将LayoutParams.WRAP_CONTENT传递到RelativeLayout.LayoutParams并更改自定义视图的高度和宽度。

制作视图方块:

    Button customView = new Button(this);
    customView.setLayoutParams(new RelativeLayout.LayoutParams(200, 200));

    RelativeLayout rlayout = (RelativeLayout) findViewById(R.id.relativeLayout1); 
    rlayout.addView(customView);

填写您可以使用的所有视图:

    Button customView = new Button(this);
    customView.setLayoutParams(new RelativeLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));

    RelativeLayout rlayout = (RelativeLayout) findViewById(R.id.relativeLayout1); 
    rlayout.addView(customView);

您还可以为布局项添加规则,如下所示:

        p.addRule(RelativeLayout.ALIGN_PARENT_LEFT);

祝福。