使用false attachtoroot和true attachtoroot膨胀布局有什么区别(布尔值)

问题描述 投票:2回答:3

使用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);
android android-layout view
3个回答
5
投票

rootattachToRoot参数一起工作。

如果您告诉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。


3
投票

attachToRoot = false时: - 返回的rootView将是来自ViewGroup的顶级R.layout.fragment_screen_3rootView仍然没有添加到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标签


0
投票

When to use which?

  • 如果要立即将childView添加到父级,请使用attachToRoot = true
  • 如果要在以后将childView添加到父级,请使用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负责。所以在这种情况下总是传递假。

© www.soinside.com 2019 - 2024. All rights reserved.