1.需要用LayoutParams
使用android.view.ViewGroup.LayoutParams 的内嵌类 LayoutParams
RelativeLayout,顾名思义,就是以“相对”位置/对齐为基础的布局方式。android.widget.RelativeLayout 有个 继承自android.view.ViewGroup.LayoutParams 的内嵌类 LayoutParams,使用这个类的实例调用 RelativeLayout.addView 就可以实现“相对布局”。
首先我们需要定义一个 RelativeLayout的布局参数relLayoutParams,如下:
RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParam(LayoutParams.FILL_PARENT,LayoutParams.WRAP_CONTENT)
子控件的宽(width),子控件的高(height),除了可以为LayoutParams.FILL_PARENT(android.view.ViewGroup.LayoutParams)等外还可以是数值;
通过LayoutParams的 addRule 方法来额外的添加别的规则了,android.widget.RelativeLayout.LayoutParams.addRule(int verb, int anchor),
其中
RelativeLayout.TRUE的值为 -1 ,所以-1或者RelativeLayout.TRUE都是可以的]、是
2.示例
Button btn = new Button(getActivity());
<span style="white-space:pre"> </span>btn.setText("remove me");
<span style="white-space:pre"> </span>btn.setOnClickListener(this);
<span style="white-space:pre"> </span>RelativeLayout.LayoutParams params ;
<span style="white-space:pre"> </span>params = new LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT);
<span style="white-space:pre"> </span>params.addRule(RelativeLayout.ALIGN_PARENT_LEFT);
<span style="white-space:pre"> </span>params.topMargin = (int) (rl.getChildCount()*tv.getHeight()*2.5f);
<span style="white-space:pre"> </span>rl.addView(btn,params);
params.addRule(RelativeLayout.ABOVE,imageViewId.getId())
params.addRule(RelativeLayout.BELOW
params.addRule(RelativeLayout.ALIGN_PARENT_RIGHT ,-1) 与
params.addRule(RelativeLayout.ALIGN_PARENT_RIGHT ,RelativeLayout.TRUE) 与
params.addRule(RelativeLayout.ALIGN_PARENT_RIGHT
params.setMargins(arg0, arg1, arg2, arg3); 或者
3.各参数含义
params.alignWithParent=true
RelativeLayout.CENTER_HORIZONTAL
RelativeLayout.CENTER_VERTICAL
RelativeLayout.CENTER_IN_PARENT
RelativeLayout.ALIGN_PARENT_BOTTOM
RelativeLayout.ALIGN_PARENT_TOP
RelativeLayout.ALIGN_PARENT_LEFT 紧贴父控件的左边边缘
RelativeLayout.ALIGN_PARENT_RIGHT
RelativeLayout.ABOVE
RelativeLayout.BELOW
RelativeLayout.LEFT_OF
RelativeLayout.RIGHT_OF
RelativeLayout.ALIGN_TOP
RelativeLayout.ALIGN_BOTTOM
RelativeLayout.ALIGN_LEFT
RelativeLayout.ALIGN_RIGHT
RelativeLayout.ALIGN_BASELINE