Skip to content

Instantly share code, notes, and snippets.

@blinkmacalahan
Created March 4, 2015 19:53
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save blinkmacalahan/1e035956f8ff110a9d3e to your computer and use it in GitHub Desktop.
Save blinkmacalahan/1e035956f8ff110a9d3e to your computer and use it in GitHub Desktop.
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
Copy link

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