在子View未知Parent的情况下解决You must call removeView() on the child's parent first的问题

交代一下发生这事的背景:

接入Ironsource的广告,反复打开banner广告的情况下,报了如下错误:
java.lang.IllegalStateException: The specified child already has a parent. You must call removeView() on the child's parent first.
    at android.view.ViewGroup.addViewInner(ViewGroup.java:4419)
    at android.view.ViewGroup.addView(ViewGroup.java:4260)
    at com.ironsource.mediationsdk.IronSourceBannerLayout$2.run(IronSourceBannerLayout.java:174)
    at android.os.Handler.handleCallback(Handler.java:754)
 

报错部分的代码如下:

IronSourceBannerLayout.this.removeAllViews();
IronSourceBannerLayout.this.mBannerView = adView;
IronSourceBannerLayout.this.addView(mBannerView, 0, layoutParams);

很明显是adView还有一个未知的parent,那得让parent移除adView才行啊。解决办法如下:

IronSourceBannerLayout.this.removeAllViews();
if (adView.getParent() != null) ((ViewGroup)adView.getParent()).removeView(adView);
IronSourceBannerLayout.this.mBannerView = adView;
IronSourceBannerLayout.this.addView(IronSourceBannerLayout.this.mBannerView, 0, layoutParams);

关键代码就是下面这一句:if (adView.getParent() != null) ((ViewGroup)adView.getParent()).removeView(adView),adView是子View。

为什么可以通过强制类型转换,因为ViewGroup实现了ViewParent接口。

 

你可能感兴趣的:(Android)