ganesh101
ganesh101

Reputation: 103

Admob Adaptive Banner ad implementation

I am replacing my current banner ad with new Adaptive banner ads. Adaptive ad size is calculatedd after width size gets captured. I am placing framelayout of adview at bottom of layout.

<Relativelayout>
..
//// linear layout above ad_view_container   
<FrameLayout
        android:id="@+id/ad_view_container"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:layout_alignParentBottom="true" />

</Relativelayout>

But now problem is, full Page gets loaded first, and after 1 -2 seconds ,whole layout shifted up and adative banner ad shows up.

So isnt this against the admob policy? how this case should be handled where i should set height for adaptive ads so this layout upshifting dont occur? searched lot but didnt find answer. Thanks in advance.

Upvotes: 3

Views: 3123

Answers (2)

Aorlinn
Aorlinn

Reputation: 778

I'm not sure, if your only intent, is to ask, whether or not this is against the policies.

But to prevent the layout from changing after some time, I use the following implementation. It also helps, when you have a more complex layout composition like I do. I use a ConstraintLayout that splits my screen in two parts in portrait mode. The banner is within one of these two parts and the ratio between them is not fixed but depending on some logic. So this implementation also works with this requirement, as it overwrite onMeasure to determined the best size depending on the available width.

public class AdBanner extends FrameLayout
{
    private AdView mAdView;
    private final DisplayMetrics mDisplayMetrics = new DisplayMetrics();

    public AdBanner(Context context)
    {
        super(context);
    }

    public AdBanner(Context context, AttributeSet attrs)
    {
        super(context, attrs);
    }

    public AdBanner(Context context, AttributeSet attrs, int defStyleAttr)
    {
        super(context, attrs, defStyleAttr);
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec)
    {
        if (!isShowBanner())
        {
            super.onMeasure(widthMeasureSpec, MeasureSpec.makeMeasureSpec(0, MeasureSpec.AT_MOST));
            return;
        }
        int width = MeasureSpec.getSize(widthMeasureSpec);
        if (width <= 0)
        {
            super.onMeasure(widthMeasureSpec, heightMeasureSpec);
            return;
        }
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);

        // That's where we determine the most accurate banner format.
        AdSize adSize = AdSize.getCurrentOrientationAnchoredAdaptiveBannerAdSize(getContext(), getDpWidth(width));
        int height = adSize.getHeightInPixels(getContext());
        int heightMode = MeasureSpec.getMode(heightMeasureSpec);
        if (heightMode != MeasureSpec.UNSPECIFIED)
        {
            height = Math.min(height, MeasureSpec.getSize(heightMeasureSpec));
        }
        setMeasuredDimension(widthMeasureSpec, MeasureSpec.makeMeasureSpec(height, MeasureSpec.getMode(heightMeasureSpec)));
    }

    protected int getDpWidth(int width)
    {
        Display display = ((WindowManager) getContext().getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay();
        display.getMetrics(mDisplayMetrics);
        return (int) (width / mDisplayMetrics.density);
    }

    protected boolean isShowBanner()
    {
        // Do your checks here, like whether the user payed for ad removement.
    }

    @Override
    protected void onLayout(boolean changed, int l, int t, int r, int b)
    {
        if (!isShowBanner())
        {
            return;
        }
        int width = r - l;
        if (width <= 0)
        {
            return;
        }
        AdSize adSize = AdSize.getCurrentOrientationAnchoredAdaptiveBannerAdSize(getContext(), getDpWidth(width));

        // Prevent the ad from beeing added with each layout cicle,
        // by checking, whether or not available size actually changed the format of the banner
        if (mAdView == null || !adSize.equals(mAdView.getAdSize()))
        {
            removeAllViews();
            mAdView = new AdView(getContext());
            mAdView.setAdSize(adSize);
            ((GameApplication) getContext().getApplicationContext()).androidInjector().getAdService().loadBannerAd(getRootActivity(this), mAdView);
            this.addView(mAdView);
        }
        mAdView.layout(0, 0, width, b - t);
    }
}

Upvotes: 1

mehul chauhan
mehul chauhan

Reputation: 1802

For this you can used below code

public class MainActivity extends AppCompatActivity {

private FrameLayout adContainerView;
private AdView adView;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    // Initialize the Mobile Ads SDK.
    MobileAds.initialize(this, new OnInitializationCompleteListener() {
        @Override
        public void onInitializationComplete(InitializationStatus initializationStatus) { }
    });
    adContainerView = findViewById(R.id.ad_view_container);
    // Step 1 - Create an AdView and set the ad unit ID on it.
    adView = new AdView(this);
    adView.setAdUnitId("ca-app-pub-3940256099942544/6300978111");
    adContainerView.addView(adView);
    loadBanner();
}

private void loadBanner() {
    // Create an ad request. 
    AdRequest adRequest =
            new AdRequest.Builder().addTestDevice(AdRequest.DEVICE_ID_EMULATOR)
                    .build();

    AdSize adSize = getAdSize();
    // Step 4 - Set the adaptive ad size on the ad view.
    adView.setAdSize(adSize);

    // Step 5 - Start loading the ad in the background.
    adView.loadAd(adRequest);
}

private AdSize getAdSize() {
    // Step 2 - Determine the screen width (less decorations) to use for the ad width.
    Display display = getWindowManager().getDefaultDisplay();
    DisplayMetrics outMetrics = new DisplayMetrics();
    display.getMetrics(outMetrics);

    float widthPixels = outMetrics.widthPixels;
    float density = outMetrics.density;

    int adWidth = (int) (widthPixels / density);

    // Step 3 - Get adaptive ad size and return for setting on the ad view.
    return AdSize.getCurrentOrientationAnchoredAdaptiveBannerAdSize(this, adWidth);
}
}

Upvotes: 0

Related Questions