Search code examples
androidadmobandroid-4.2-jelly-bean

Admob ads displaying over buttons on Jelly Bean


I was testing an app for compatibility with Jelly Bean when I noticed that a Admob ads (Admob SDK 6.1.0) were being displayed on top of the buttons in the app. The layout I'm using is:

        <ImageView android:id="@+id/line"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_below="@id/spinner"
            android:maxWidth="350sp"
            android:layout_marginTop="5dip"
            android:layout_centerHorizontal="true"
            android:src="@drawable/line"/>
        <View android:id="@+id/ad" 
            android:layout_width="fill_parent" 
            android:layout_height="wrap_content"
            android:layout_below="@id/line"
            android:layout_marginTop="5dip"
            android:layout_marginBottom="5dip"/>
        <Button android:id="@+id/generate"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_below="@id/ad"
            android:layout_centerHorizontal="true"
            android:textStyle="bold"
            android:textColor="#000000"
            android:text="@string/generate"/>

What happens is that when the ad loads, it displays on top of the button. In previous versions of Android (ICS and older), the ad would load and the button would be pushed down to accommodate the ad. Does anyone know how I can restore this functionality on Jelly Bean? Thanks!


Solution

  • My solution to this problem is to implement the AdListener interface to manually set the top margin of the button when an ad is loaded. This moves the button down and prevents it from being covered up by the ad.

    @Override
    public void onReceiveAd(Ad arg0) {      
        // Move the generate button down by the height of the ad on load
        MarginLayoutParams params = (MarginLayoutParams)generateBtn.getLayoutParams();
        params.topMargin = AdSize.BANNER.getHeightInPixels(this);
        generateBtn.setLayoutParams(params);
    }
    

    And since this problem only happens on Jelly Bean, only set the AdListener if running on Jelly Bean

    if(Build.VERSION.SDK_INT == Build.VERSION_CODES.JELLY_BEAN)
        ad.setAdListener(this);