java.lang.IllegalStateException: The specified child already has a parent. You must call removeView() on the child's parent first.
這個異常讓人很頭疼,你必須要在parent上調用removeView移除掉你要重複使用的這個view纔可以,有時候不知道你的view被哪一個parent給綁定了,所以很頭疼。下面給出解綁方法的思路:
解決思路1:幫孩子找父母,然後斷絕親子關係:
三步走:
假設你的子view就叫child_view
1、 找出parent
ViewParent parent = child_view.getParent();
正常想法,直接parent.removeView不就可以了嘛,可是你會發現ViewParent沒有removeView方法。接下來:
2、找出這個parent具體是什麼類型
if(parent!=null)
Log.i("who_are_you",parent.getClass().toString());
直接輸出,然後你會看到輸出的類型是什麼,我這邊是FrameLayout,真相大白,接下來解綁:
3、直接強轉,解綁:
FrameLayout mFrameLayout = (FrameLayout)parent;
mFrameLayout.removeView(child_view);
熟悉更多android代碼以後,才發現其實有更簡單的方法,只需一行代碼:
解決思路2:給孩子找個繼父母,然後斷絕親子關係:
((ViewGroup)childView.getParent()).removeView(childView);
當然,實際開發你得判斷這個childView的父view是否爲空 。
OK,解完,收工。
轉載註明出處:https://blog.csdn.net/qq_35584878/article/details/93038872