我在layout/activity.xml
我想通过以下方式以编程方式添加一些元素:
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)中添加这些元素,我该怎么做?
答案 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);
祝福。