LayoutInflater学习总结

----参考,转载,借用来源:http://blog.csdn.net/guolin_blog/article/details/12921889

Activity类中onCreate方法中,setContentView()方法,之所以是setContentView,是因为系统会自动在我们的Activity的布局文件的最外层包一层FrameLayout,所以方法才是setContentView,而不是setView,具体原理解析可以用下面这张图来表示:

而我们经常在xml布局文件中设置的layout_width,layout_height 其实相对父布局而言的,所以我们最外层的layout_width以及layout_height属性之所以有效果,是因为系统自动在最外面套了一层FrameLayout。

所以在我们自定义一个view,并添加到当前布局的时候需要自己手动的传入一个LayoutParameter,才能设置大小,左右边距等等属性。。----待验证

2. LayoutInflater的使用方法:

  a. LayoutInflater inflater = LayoutInflater.from(context);

  b. LayoutInflater inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);

a方法是b方法的精简版

3.inflate方法的重构

  inflater(resouceId,root) : resourceId是指要加载的布局的资源文件Id,root指的是给该布局外层再嵌套一个父布局,如果不需要就直接传入null。这样就成功创建了一个布局的实例,之后再将它动态添加到父布局中就可以了。

  inflater(resouceId,root,attachToRoot): 前两个参数和上面一样:

    a. 如果root为null,则attachToRoot失去作用,设置成任何值都没有一样

    b. 如果root不为null,attachToRoot为true,则为布局添加一个父布局,即root

    c. 如果root不为null,attachToRoot为false,则会将该布局的layout_width及layout_height属性设置成最外层的布局的两个属性一致。即如果最外层是match_parent,那么该布局也是match_parent

    d. 不设置attachToRoot,如果root不为null,则attachToRoot默认为true;

    

原文地址:https://www.cnblogs.com/shinhwa/p/5209350.html