您可以将合并标签与片段一起使用吗? [英] Can you use the merge tag with fragments?

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

问题描述

如果我使用 merge 标签作为片段布局的父标签,我会遇到两个问题:

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

  • 首先,在 onCreateView() 中,如果我指定不附加到根目录,则会出现错误:

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

android.view.InflateException: <merge/>只能与有效的 ViewGroup 根和 attachToRoot=true 一起使用

如果我确实附加到 root,我会收到错误:

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

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

我在这里找到了另一个问题的一个很好的答案,它说片段库会自动将子视图附加到您在替换中指定的父视图组.建议是您因此需要将 attachToRoot 设置为 false.对于 merge 标记,它是必需的.

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.

是否可以绕过这些规则中的任何一个来使用 merge 标记来进行片段的布局?

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?

没有.正如您已经看到的,当您扩充一个以 merge 标记为根的布局文件时,您必须将其附加到有效的父 ViewGroup.将其附加到 onCreateView 中的容器是不正确的,因为该方法返回的 View 将被框架添加.

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.

你总是可以在 onCreateView 方法中创建一个包装布局来附加膨胀的布局(并返回这个包装布局),但这将使 merge标记优化没用,因为您可以从一开始就在 xml 布局文件中添加包装器布局:

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天全站免登陆