一个View的index越大,说明它越在上面
P.s.index为-1则在线性布局位于底部(-1具体原因不清楚)
addView
added in API level 1
public void addView (View child, int index, ViewGroup.LayoutParams params)
Adds a child view with the specified layout parameters.
Parameters | |
---|---|
child | View : the child view to add
|
index | int : the position at which to add the child or -1 to add last
|
params | ViewGroup.LayoutParams : the layout parameters to set on the child |
3个参数介绍:
子布局,子布局位置(-1表示线性布局中置于底部,0表示置于顶部,如果多个view重叠,则index越大,该view则越处于上层),添加子布局的父布局参数(如果有原父布局,则原父布局参数失效)
配合LayoutInflater来动态加载布局
LayoutInflater layoutInflater=LayoutInflater.from(this); view1=layoutInflater.inflate(R.layout.activity_test01_item02,rl,false);
rl.addView(view1);
//这种方法加载不了view,会报错
LinearLayout rl_item =findViewById(R.id.ll_item01);
rl.addView(rl_item);
ViewGroup.LayoutParams
官方构造方法:
ViewGroup.LayoutParams(Context c, AttributeSet attrs) Creates a new set of layout parameters. |
ViewGroup.LayoutParams(int width, int height) Creates a new set of layout parameters with the specified width and height. |
ViewGroup.LayoutParams(ViewGroup.LayoutParams source) Copy constructor. |
P.s. view.getLayoutParams()是获取父布局的LayoutParams参数,不是获取自己的LayoutParams参数
RelativeLayout.LayoutParams params1 = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
params1.leftMargin = 100;
则必须rl.addView(view1,params1);而且view1最外层layout参数失效
RelativeLayout.LayoutParams params1 = (RelativeLayout.LayoutParams) view1.getLayoutParams();
params1.leftMargin = 100;则直接修改父布局的layou参数并且立即生效无需addview(param1)来设置
(其实也可以直接在view布局xml中直接修改)