Created
March 4, 2015 19:53
-
-
Save blinkmacalahan/1e035956f8ff110a9d3e to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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.