您可以使用碎片合并标签? [英] Can you use the merge tag with fragments?

查看:127
本文介绍了您可以使用碎片合并标签?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我使用合并标记为我的片段布局的父标签,我遇到两个问题:

  • 首先,在 onCreateView(),如果我不指定要附加到根,我得到的错误:

    android.view.InflateException:其中,合并/>只能用于具有有效的ViewGroup根和attachToRoot =真

  • 和如果我做附加到根,我得到的错误:

    java.lang.IllegalStateException:指定的孩子已经有一个父。你必须先调用removeView()孩子的父母。

我找到了一个很好的答案,在这里另外一个问题说,片段库将孩子自动连接到您指定的替换父视图组。该建议是,你需要因此设置 attachToRoot 。对于合并标签,它的要求。

是否有可能解决其中任一规则,使用合并标记片段的​​布局?

解决方案
  

是否有可能解决其中任一规则,使用合并   标签片段的布局?

没有。正如你已经看到的,当你夸大其具有合并标签作为其根您布局文件必须将其连接到一个有效的父的ViewGroup 。它附着在容器中的 onCreateView 是不正确的查看由该方法返回将被框架添加。

您总是可以只建立在 onCreateView 的方法,用来连接充气布局的封装布局(并返回这个包装的布局),而这会令合并标签优化没用,因为你可以添加封装布局,从一开始的XML布局文件:

  @覆盖
公共查看onCreateView(LayoutInflater充气,容器的ViewGroup,捆绑savedInstanceState){
     的LinearLayout包装=新的LinearLayout(getActivity()); // 例如
     inflater.inflate(R.layout.layout_with_merge_as_root,包装,真正的);
     返回包装;
}
 

If I use the merge tag as the parent tag for my fragment's layout, I run into two issues:

  • first, in onCreateView(), if I specify NOT to attach to root, I get the error:

    android.view.InflateException: <merge /> can be used only with a valid ViewGroup root and attachToRoot=true

  • and if I DO attach to root, I get the error:

    java.lang.IllegalStateException: The specified child already has a parent. You must call removeView() on the child's parent first.

I found a nice answer to another question here saying that the fragment library will automatically attach the child to the parent view group you specify in replace. The suggestion was that you needed to therefore set attachToRoot to false. For the merge tag, it's required.

Is it possible to get around either of these rules to use the merge tag for a fragment's layout?

解决方案

Is it possible to get around either of these rules to use the merge tag for a fragment's layout?

No. As you already seen, when you inflate a layout file which has the merge tag as its root you must attach it to a valid parent ViewGroup. Attaching it to the container in the onCreateView is incorrect as the View returned by that method will be added by the framework.

You could always just create a wrapper layout in the onCreateView method to which to attach the inflated layout(and return this wrapper layout), but this will make the merge tag optimization useless as you could add the wrapper layout in the xml layout file from the start:

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
     LinearLayout wrapper = new LinearLayout(getActivity()); // for example
     inflater.inflate(R.layout.layout_with_merge_as_root, wrapper, true);
     return wrapper;
}

这篇关于您可以使用碎片合并标签?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆