Correctly disable AdMob ads

前端 未结 9 1647
感情败类
感情败类 2020-12-02 05:13

I am integrating AdMob into my app and I wonder how to disable Ads correctly. I want to give the user the ability to disable them. I don\'t want to get any problems with AdM

9条回答
  •  独厮守ぢ
    2020-12-02 05:54

    Unfortunately the setVisibility(View.GONE); + setEnabled(false) combo does not work universally on all android versions / devices. Depending on when do you invoke it you may end up hanged in empty screen (no NPE, just blank screen).

    So far the only solution that works for me is:

    For Activity:

    protected void removeAdView(int adViewId) {
        View view = getWindow().getDecorView();
        View adView = view.findViewById(adViewId);
    
        if (adView != null) {
            ViewGroup parent = (ViewGroup) adView.getParent();
            parent.removeView(adView);
            parent.invalidate();
        }
    }
    

    For Fragment:

    protected void removeAdView(View topView, int adViewId) {
        View adView = topView.findViewById(adViewId);
    
        if (adView != null) {
            ViewGroup parent = (ViewGroup) adView.getParent();
            parent.removeView(adView);
            parent.invalidate();
        }
    }
    

    This solution is based on @Quartertone's answer but extended to be more universal (i.e. works with all ViewGroups not just LinearLayout). Just put these methods in your base Activity/Fragment classes.

提交回复
热议问题