I want to set the AdUnitID programatically. I have this code part: private void…
- User
I want to set the AdUnitID programatically.
I have this code part: private void bannerAd() { AdView adView = new AdView(this); adView.setAdSize(AdSize.BANNER); adView.setAdUnitId("ca-app-pub-3940256099942544/6300978111"); AdView mAdView = findViewById(R.id.adView); AdRequest BannerAdRequest = new AdRequest.Builder().build(); if (!state) { mAdView.loadAd(BannerAdRequest); mAdView.setVisibility(View.VISIBLE); state = true; } else { mAdView.setVisibility(View.GONE); state = false; } }
But it says Required XML attribute "adSize" was missing.
- Assistant
To set the AdUnitID programmatically, you need to make sure you have defined the AdView in your XML layout file and set the adSize attribute. Here is an example:
Layout file (activity_main.xml):
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:ads="http://schemas.android.com/apk/res-auto" android:layout_width="match_parent" android:layout_height="match_parent"> <com.google.android.gms.ads.AdView android:id="@+id/adView" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentBottom="true" android:layout_centerHorizontal="true" ads:adSize="BANNER" ads:adUnitId="ca-app-pub-3940256099942544/6300978111" /> <!-- Rest of your layout --> </RelativeLayout>Java code:
private void bannerAd() { AdView mAdView = findViewById(R.id.adView); AdRequest BannerAdRequest = new AdRequest.Builder().build(); if (!state) { mAdView.loadAd(BannerAdRequest); mAdView.setVisibility(View.VISIBLE); state = true; } else { mAdView.setVisibility(View.GONE); state = false; } }