Fragment onCreateView inflate注意事项
2015-09-01 19:37
260 查看
一
@Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // TODO Auto-generated method stub View root = inflater.inflate(layoutId(), container, false); return root; }二
@Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // TODO Auto-generated method stub View root = inflater.inflate(layoutId(), null); return root; }
方法2最终调用了方法1,即inflate(int resource, ViewGroup root, boolean attachToRoot),所以直接看方法1.如果root不为空,attachToRoot为false的情况下,文档说的很明白:If false, root is only used to create the correct subclass of LayoutParams for the root view in the XML,即root只用来创建母布局的参数信息。而为true,则添加到母布局。因为我们控制fragment时要手动add,所以此处attachToRoot一定是false。
再反过来看,如果用了方法2,root一定要传null,此时子view不会得到母view的布局信息,子view里一堆的match_parent也就毫无用途。
总结:90%的情况下,我们使用fragment此处一定要用方法1. 有一种情况,如创建dialog fragment时,不需要得到母布局参数信息可以用方法2.
补充:上文代码里的layoutId()是个虚函数,用来在子类里实现。子类只需return R.layout.*就可以了,不必每个fragment都重写onCreateView了。在onViewCreated里根据传来的参数root去实例化各个控件。
相关文章推荐
- Android Camera HAL浅析
- Git入门
- ubuntu安装redis
- 如何确定map以及reduce的个数
- Codeforces Round 313 找规律
- php中self和$this的用法
- 观察者KVO
- 贝塞尔曲线
- String对象
- [LintCode] Find the Weak Connected Component in the Directed Graph
- [Leetcode] Different Ways to Add Parentheses
- VIM配置笔记(cscope+NERDTree)
- Safari的常用快捷键
- 我的程序员未婚夫
- 【UVA796】【无向图割边】
- Windows 端口和任务 查看 相关命令
- CRgn::CreateEllipticRgnIn
- 第三方加载图片
- 获取本机外网ip获取位置
- 散列操作的基本例程(1)