现在的位置: 首页 > 综合 > 正文

LayoutParams和LayoutInflater理解

2018年05月06日 ⁄ 综合 ⁄ 共 1117字 ⁄ 字号 评论关闭
LayoutParams继承于Android.view.ViewGroup.LayoutParams 
LayoutParams封装了Layout的高,宽等信息,假设一个区域由一个Layout占领,如果将一个View添加到Layout中,需要告诉Layout用户期望的布局方式,即将一个认可的LayoutParams传递进去。 
LayoutParams描述的宽高的值可以设置为下边2个值中的任何一种: 
一个确定的值; 
FILL_PARENT,即View希望和父容器一样大; 
WRAP_CONTENT,指当前的View的大小只需要包裹住View里面的内容即可。 
Java代码 
private LinearLayout layout; 
layout =(LinearLayout)findViewById(R.id.layout); 
TextView view = newTextView(Activity01.this);  
view.setText("Text View"); 
LinearLayout.LayoutParamsparams = new LinearLayout.LayoutParams( 
LinearLayout.LayoutParams.FILL_PARENT, 
LinearLayout.LayoutParams.WRAP_CONTENT); 
layout.addView(view,params); 


LayoutInflater的作用类似于findViewById(),不同点是LayoutInflater是用来找layout下xml布局文件,并且实例化!而findViewById()是找具体xml下的具体widget控件(如:Button,TextView等)。LayoutInflater的作用是将一个XML文档变成一个View,使用的典型是在Activity的onCreate方法里 
Java代码 
LayoutInflater inflate =(LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);//LayoutInflater需要通过getSystemService方法来获得,而不能直接实例化 
RelativeLayout layoutLeft =(RelativeLayout) inflate.inflate(R.layout.left,null);//调用inflate方法将left.xml进行解析,并生成一个RelativeLayout布局 

抱歉!评论已关闭.