Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
import android.content.Context;
import android.util.AttributeSet;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import java.util.ArrayList;
* When using fragments, the xml used for the Fragment's view (that is used in onCreateView) cannot
* have the root element be a <merge/> or <include/> tag. To fix this deficiency, this
* View will serve as a valid view to inflate a merge or include element into. When this view is
* attached, it will then remove itself from its parent and add all its children to the parent.
public class ReParentViewGroup extends FrameLayout {
public ReParentViewGroup(Context context) {
this(context, null);
public ReParentViewGroup(Context context, AttributeSet attrs) {
this(context, attrs, 0);
public ReParentViewGroup(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
public void onAttachedToWindow() {
ViewGroup parent = (ViewGroup) getParent();
//remove myself
//get my children
ArrayList<View> children = new ArrayList<>();
for (int i = 0; i < getChildCount(); i++) {
View child = getChildAt(i);
//remove my children
//add my children to my parent
for (View v : children) {

This comment has been minimized.

Copy link

@Tadas44 Tadas44 commented Mar 5, 2015

I Use tags in layout and when I inflate it and attach to root it works just fine. Done dozen custom views and none of them crashed.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment