在代码中动态创建步骤
1.创建一个根布局(一般都属于VIewGroup的子类),一般都是常用布局,通常根布局都是继承ViewGroup去写的
2.创建一个根布局LayoutParams,所有的LayoutParam子类都是继承于ViewGroup.LayoutParams,而所有的根布局类型里面一般都有对应类型的LayoutParams。比如说RelativeLayout里面的是RelativeLayout.LayoutParams,LinearLayout里面对应的是LinearLayout.LayoutParams
3.要往什么类型布局添加子View,就创建什么类型的LayoutParams。
4.设置LayoutParam的各类型参数,可以控制位置,边距,大小等。
5.调用addView方法添加到根布局中。
6.在setContentView()中将创建的布局添加进去。或者其他想要的地方。总之要先创建完成,再添加。
以RelativeLayout为例
添加一个View
private void addOne(){
mRoot.removeAllViews();
Button view1=new Button(mRoot.getContext());
RelativeLayout.LayoutParams lp = generateLp();
//根据需要可以添加更多Rule
lp.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
view1.setLayoutParams(lp);
view1.setText("BTN1");
mRoot.addView(view1);
}
添加多个View
private void addRlView(){
mRoot.removeAllViews();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
mRoot.setBackground(getDrawable(R.mipmap.ic_launcher));
}else{
mRoot.setBackground(getResources().getDrawable(R.mipmap.ic_launcher));
}
Button view1=new Button(mRoot.getContext());
RelativeLayout.LayoutParams lp = generateLp();
lp.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
view1.setLayoutParams(lp);
view1.setText("BTN1");
mRoot.addView(view1);
Button view2=new Button(mRoot.getContext());
lp=null;
lp = generateLp();
lp.addRule(RelativeLayout.ALIGN_PARENT_LEFT);
view2.setLayoutParams(lp);
view2.setText("BTN2");
view2.setId(R.id.basic);
Log.d("addRlView", "addRlView2: "+view2.getId());
mRoot.addView(view2);
Button view3=new Button(mRoot.getContext());
lp=null;
lp = generateLp();
lp.addRule(RelativeLayout.BELOW,view2.getId());
view3.setLayoutParams(lp);
view3.setId(R.id.basic);
Log.d("addRlView", "addRlView3: "+view3.getId());
view3.setText("BTN3");
mRoot.addView(view3);
Button view4=new Button(mRoot.getContext());
lp=null;
lp = generateLp();
//给view3需要设置一个id,否者不会显示预期效果,不设置Id默认为-1.
lp.addRule(RelativeLayout.BELOW,view3.getId());
view4.setLayoutParams(lp);
view4.setId(R.id.basic);
Log.d("addRlView", "addRlView4: "+view4.getId());
view4.setText("BTN4");
mRoot.addView(view4);
}
private RelativeLayout.LayoutParams generateLp(){
return new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
}