介绍
- android.view.LayoutInflater
- public abstract class LayoutInflater extends Object
- 加载布局的任务通常都是在Activity中调用setContentView()方法来完成的,其实setContentView()方法的内部也是使用LayoutInflater来加载布局的,只不过这部分源码是internal的
两种获取LayoutInflater的方式:
//当前要获得LayoutInflater的context
LayoutInflater layoutInflater = LayoutInflater.from(context);
LayoutInflater layoutInflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
方法
以下是常见的重载方式:
public View inflate (int resource,
ViewGroup root)
public View inflate (int resource,
ViewGroup root,
boolean attachToRoot)
//以下三条代码等价
LayoutInflater.from(context) .inflate(R.layout.title,TitleLayout,true)
LayoutInflater.from(context) .inflate(R.layout.title,TitleLayout)
View view=LayoutInflater.from(context) .inflate(R.layout.title,TitleLayout,false)
titleLayout.addView(view)
参数解析:
- int resource:要加载的布局文件id
- ViewGroup root:给加载好的布局再添加一个父布局,如果为null,将会导致加载好的的布局属性设置失效
- boolean attachToRoot:为true时,底层会自动调用addview(),为这个View添加父布局;当为false时表示只让我们在父布局中声明的layout属性生效,但不为这个View添加父布局,因为一旦View有了父布局之后,它就不能添加到ListView中了