LayoutInflater、LayoutParams实现activity和layout相关联
- LayoutInflater的作用类似于findViewById(),不同点是LayoutInflater是用来找layout下xml布局文件,而findViewById()是找具体xml下的具体widget控件(Button,TextView)。LayoutInflater的作用是将一个XML文档变成一个View并添加到相应的layout中去,一般在Activity的onCreate方法里使用:
LayoutInflater inflater=(LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
RelativeLayout relativeLayout=inflater.inflate(R.layout.left,null); - LayoutParams继承于Android.view.ViewGroup.LayoutParams
LayoutParams封装了view的宽和高:
:FILL_PARENT,即View希望和父容器一样大;
:WRAP_CONTENT,指当前的View的大小只需要包裹住View里面的内容即可。
LinearLayout layout=new LinearLayout(this);
RelativeLayout relativeLayout=inflater.inflate(R.layout.left,null);
LayoutParams params=new LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT);
向layout中添加组件可以有两种方式:
- layout.addView(relativeLayout,100,100);//100,100是relativeLayout的高度和宽度
- layout.addView(relativeLayout,params);//将params封装的view的大小传进去