Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
package com.your.packagename.here;
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);
}
@Override
public void onAttachedToWindow() {
super.onAttachedToWindow();
ViewGroup parent = (ViewGroup) getParent();
//remove myself
parent.removeView(this);
//get my children
ArrayList<View> children = new ArrayList<>();
for (int i = 0; i < getChildCount(); i++) {
View child = getChildAt(i);
children.add(child);
}
//remove my children
removeAllViews();
//add my children to my parent
for (View v : children) {
parent.addView(v);
}
}
}
@Tadas44

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