使用false attachtoroot和true attachtoroot(boolean)膨胀布局有什么区别?
这是一个代码:
ViewGroup rootView = (ViewGroup) inflater.inflate(
R.layout.fragment_screen_3, container, false);
和:
ViewGroup rootView = (ViewGroup) inflater.inflate(
R.layout.fragment_screen_3, container, true);
root
和attachToRoot
参数一起工作。
如果您告诉inflate()
将膨胀的视图附加到根视图,那么您膨胀的布局将作为子项添加到根。
以下是inflate()
方法的简化:
public View inflate (int resource, ViewGroup root, boolean attachToRoot) {
View inflatedView = inflate(resource); // Inflate the desired view
if (attachToRoot) {
root.addView(inflatedView);
}
}
如果要膨胀最终将附加到父视图的视图,这很有用,例如,如果要使用相同的布局对多个视图进行充气以动态填充ListView。
当attachToRoot
= false时:
- 返回的rootView
将是来自ViewGroup
的顶级R.layout.fragment_screen_3
,rootView
仍然没有添加到container
。(可以添加到另一个视图组父母)
- 如果R.layout.fragment_screen_3
中的顶部标签是<merge>
,它会引发异常。
当attachToRoot
= true时:
- 返回rootView
将是container
。
- R.layout.fragment_screen_3
的内容将作为container
的一部分添加(就像当你使用attachToRoot
= false时,然后调用container.addView(rootView);
- 可以在<merge>
中使用R.layout.fragment_screen_3
标签
attachToRoot = true
。attachToRoot = false
。您还应该使用
attachToRoot = false
当您不负责添加childView时。
例如。在添加片段时
public View onCreateView(LayoutInflater inflater,ViewGroup parent,Bundle bundle)
{
super.onCreateView(inflater,parent,bundle);
View view = inflater.inflate(R.layout.image_fragment,parent,false);
.....
return view;
}
如果你传递第三个参数为true,那么你会得到IllegalStateException。
getSupportFragmentManager()
.beginTransaction()
.add(parent, childFragment)
.commit();
因为您已经错误地在onCreateView()中添加了子片段。调用add(parent, childFragment)
将抛出IllegalStateException,因为已添加子视图。
这里你不负责添加childView,FragmentManager负责。所以在这种情况下总是传递假。