Reputation: 7421
I am trying to use include layout for the adView with data binding. But, it throws me an error:
java.lang.IllegalStateException: The ad size and ad unit ID must be set before loadAd is called.
Now what I am doing is, in my main activity layout, I have included the layout with variable adId for the adUnitId like this:
<include
android:id="@+id/adViewInclude"
layout="@layout/include_ads"
app:adId="@{@string/main_activity_banner_ad_unit_id}" />
My include_ads.xml
is like this:
<layout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<data>
<variable
name="adId"
type="String" />
</data>
<FrameLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:orientation="vertical">
<com.google.android.gms.ads.AdView
android:id="@+id/adView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:adSize="SMART_BANNER"
app:adUnitId="@{adId}" />
</FrameLayout>
</layout>
Now in my Activity's onCreate
method I am calling this method at last:
private void loadAds() {
mBinding.executePendingBindings();
AdRequest adRequest = new AdRequest.Builder().build();
mBinding.mainContent.adViewInclude.adView.loadAd(adRequest);
}
But, it is throwing an error. What's going wrong here?
Upvotes: 0
Views: 893
Reputation: 80
Another way to do it is by creating the adView programatically. To do this, first you will need to create a view group.
Create View group in layout file: You only need id, width, height
<FrameLayout android:id="@+id/homeAdContainer"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
In your activity/fragment file, programaticaly add in the adView:
AdView adView = new AdView(this);
adView.setAdUnitId(AdID);
adView.setAdSize(AdSize);
ViewGroup adContainerView = (ViewGroup) findViewById(R.id.homeAdContainer);
adContainerView.removeAllViews();
adContainerView.addView(adView);
Upvotes: 0