Search code examples
androidxmlandroid-layoutlayoutbanner-ads

Placing Android Banner Ads over ScrollView


I want to place two banner ads in my activity- one at the top, another on the bottom of the screen. I have LinearLayout as the main layout and it contains a ScrollView that is larger than the screen. If I put the following XML code at the end of the ScrollView, it goes out of the screen. Clearly it needs to be drawn on top of the ScrollView. How can I do that?

 <com.google.android.gms.ads.AdView
        xmlns:ads="http://schemas.android.com/apk/res-auto"
        android:id="@+id/adView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_alignParentBottom="true"
        android:layout_gravity="center"
        ads:adSize="BANNER"
        ads:adUnitId="ca-app-pub-3940256099942544/6300978111">
    </com.google.android.gms.ads.AdView> 

Solution

  • You can achieve this by putting the following code to your design file.

    Change your Xml File

    <?xml version="1.0" encoding="utf-8"?>
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:tools="http://schemas.android.com/tools"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical"
        tools:context="DemoActivity">
    
    
        <com.google.android.gms.ads.AdView xmlns:ads="http://schemas.android.com/apk/res-auto"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentBottom="true"
            android:layout_centerHorizontal="true"
            android:layout_gravity="center"
            ads:adSize="BANNER"
            ads:adUnitId="ca-app-pub-3940256099942544/6300978111"></com.google.android.gms.ads.AdView>
    
        <ScrollView
            android:layout_width="match_parent"
            android:layout_height="0dp"
            android:layout_weight="1"></ScrollView>
    
    
        <com.google.android.gms.ads.AdView xmlns:ads="http://schemas.android.com/apk/res-auto"
            android:id="@+id/adView"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentBottom="true"
            android:layout_centerHorizontal="true"
            android:layout_gravity="center"
            ads:adSize="BANNER"
            ads:adUnitId="ca-app-pub-3940256099942544/6300978111">
        </com.google.android.gms.ads.AdView>
    
    </LinearLayout>