作用:用来实例化一个XML文件到指定View中。与findViewById类似,不同的是LayoutInflater找的layout文件下的没有被载入或需动态被载入,
对于已经载入的Activity可以使用findViewById来获得其中的界面元素。
获得LayoutInflater的几种方式:
-
1.LayoutInflater inflater = getLayoutInflater(); //调用Activity的getLayoutInflater() Returns LayoutInflater The shared LayoutInflater. 2.LayoutInflater inflater =LayoutInflater.from(context); //Obtains the LayoutInflater from the given context. 3.LayoutInflater inflater =(LayoutInflater)context.getSystemService (Context.LAYOUT_INFLATER_SERVICE); //A LayoutInflater for inflating layout resources in this context
从源码得到三种都是调用Context.getSystemService(),它根据NAME来取得对应的Object然后转换成相应服务对象。
LAYOUT_INFLATER_SERVICELayoutInflater取得xml里定义的view。
返回View:
使用inflate方法。
inflate的作用是将一个XML中定义的布局找出来。
Resource:要加载的布局文件的id
root:给加载好的布局添加一个父布局
-
View view = inflater.inflate(R.layout.newview, null); setContentView(view);//显示