You must first remove the child view from its parent.
If your project is in Kotlin, your solution will look slightly different than Java. Kotlin simplifies casting with as?
, returning null if left side is null or cast fails.
(childView.parent as? ViewGroup)?.removeView(childView)
newParent.addView(childView)
If you need to do this more than once, add this extension to make your code more readable.
childView.removeSelf()
fun View?.removeSelf() {
this ?: return
val parentView = parent as? ViewGroup ?: return
parentView.removeView(this)
}
It will safely do nothing if this View is null, parent view is null, or parent view is not a ViewGroup