xamarin.formsadmobcontrolsadsadview

Xamarin.Forms Google Services AdMob


I'm trying to implement AdMob in my Xamarin.Forms app (Android version for now). Here is what I have done so far:

  1. Created a custom control, AdViewControl, in my shared project:
public class AdControlView : Xamarin.Forms.View
{
}
  1. In my page in which to show the ad, I added the custom control in xaml:
xmlns:ads="clr-namespace:MyFeelingBuddyTwo.Views"
<ads:AdControlView BackgroundColor="Red"/> 
  1. In the Android project (AndroidManifest.xml), within :

    
<meta-data
    android:name="com.google.android.gms.ads.APPLICATION_ID"
    android:value="ca-app-pub-myappid"/>
<activity android:name="com.google.android.gms.ads.AdActivity"
android:configChanges="keyboard|keyboardHidden|orientation|screenLayout|uiMode|screenSize|smallestScreenSize"/>

  1. In the Android project still, I created an AdViewRenderer:

    
[assembly: ExportRenderer(typeof(MyFeelingBuddyTwo.Views.AdControlView), typeof(AdViewRenderer))]
namespace MyFeelingBuddyTwo.Droid
{
    class AdViewRenderer : ViewRenderer<Views.AdControlView, AdView>
    {
        string adUnitId = "myadunitid";
        AdSize adSize = AdSize.SmartBanner;
        AdView adView;

        AdView CreateAdView()
        {
            if (adView != null)
                return adView;

            adView = new AdView(Forms.Context);
            adView.AdSize = adSize;
            adView.AdUnitId = adUnitId;
            var arParams = new LinearLayout.LayoutParams(LayoutParams.WrapContent, LayoutParams.WrapContent);
            adView.LayoutParameters = arParams;
            adView.LoadAd(new AdRequest.Builder().Build());

            return adView;
        }

        protected override void OnElementChanged(ElementChangedEventArgs<AdControlView> e)
        {
            base.OnElementChanged(e);
            if(Control == null)
            {
                CreateAdView();
                SetNativeControl(adView);
            }
        }
    }
}

  1. In MainActivity, intialize MobileAds just before loading the app:

    MobileAds.Initialize(ApplicationContext, "ca-app-pub-appid");
            

When I run, I get the red background but no ads are loaded. Any ideas?


Solution

  • In the AdControlView class, I added :

    
        public static readonly BindableProperty AdUnitIdProperty = BindableProperty.Create("AdUnitId", typeof(string), typeof(AdControlView));
            
            public string AdUnitId
            {
                get { return (string)GetValue(AdUnitIdProperty); }
                set { SetValue(AdUnitIdProperty, value); }
            }
    
    

    Now I can see "Test Ad" in the banner placeholder.