Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
229 views
in Technique[技术] by (71.8m points)

android - Can you use the merge tag with fragments?

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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;
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...