Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 620
Plantage Avatar asked Nov 12 '12 17:11

Plantage


People also ask

Can fragments be used in multiple activities?

You can use multiple instances of the same fragment class within the same activity, in multiple activities, or even as a child of another fragment.

What is the advantage of using fragments?

The Fragment class in Android is used to build dynamic User Interfaces and should be used within the activity. The biggest advantage of using fragments is that it simplifies the task of creating UI for multiple screen sizes. An activity can contain any number of fragments.


1 Answers

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; } 
like image 188
user Avatar answered Oct 03 '22 23:10

user