【问题标题】:Native Admob Ads in Xamarin.Forms. Are there any ready-made solutions / examples?Xamarin.Forms 中的原生 Admob 广告。有没有现成的解决方案/例子?
【发布时间】:2018-10-03 09:43:44
【问题描述】:

我需要在 Xamarin.Forms 中实现原生广告。但我没有在 Xamarin.Forms 上找到任何示例。 也许有人有在 Xamarin.Forms 上使用原生广告的示例,可以分享。

我尝试做的事情的例子:

安卓:

[assembly: Dependency(typeof(NativeAd))]
namespace Ads.Droid.Platform.Renderers.Ad
{
    public class NativeAd : AdListener, INativeAd
    {
        Context context = Android.App.Application.Context;
        NativeExpressAdView mAdView;

       public void Show()
        {   
            var videoOptions = new VideoOptions.Builder().SetStartMuted(false).Build();
            var adOptions = new NativeAdOptions.Builder().SetVideoOptions(videoOptions).Build();
            AdLoader adLoader = new AdLoader.Builder(context, "ca-app-pub-3940256099942544/2247696110").WithNativeAdOptions(adOptions).Build();

            var request = new AdRequest.Builder();
            foreach (var item in TestDevice.GetTestDevices())
                request.AddTestDevice(item);

            adLoader.LoadAd(request.Build());   
        }
    }
}

或:

[assembly: Dependency(typeof(NativeAd))]
namespace Ads.Droid.Platform.Renderers.Ad
{
    public class NativeAd : AdListener, INativeAd
    {
        NativeExpressAdView mAdView;

       public void Show()
        {   
            mAdView = new NativeExpressAdView(Android.App.Application.Context)
            {
                AdUnitId = "ca-app-pub-3940256099942544/2247696110",
                AdSize = AdSize.MediumRectangle
            };
            var request = new AdRequest.Builder();
            foreach (var item in TestDevice.GetTestDevices())
                request.AddTestDevice(item);
            mAdView.LoadAd(request.Build());    
        }
    }
}

在 iOS 中没有这样做,但我还需要一个示例。 也许有些事情需要改变或完成。 请帮帮我。

【问题讨论】:

  • 嘿,你解决了这个问题吗?
  • @LucasZhang-MSFT 此问题已暂停。问题是帐户中没有原生广告。

标签: xamarin.forms xamarin.ios xamarin.android admob ads


【解决方案1】:

这里是使用新的NativeAdView 实施适用于 Android 的 Google AdMob 原生广告的来源。

此来源将在您的共享中,

public class NativeAdView : ContentView
{
    public NativeAdView()
    {
        this.HeightRequest = 100;
        this.Margin = new Thickness(8, 8, 8, 0);

        SetPlaceholderContent();
    }

    private void SetPlaceholderContent()
    {
        var placeholderGrid = new Grid();
        var placeHolderText = new Label
        {
            Text = "AD",
            FontSize = 48,
            FontAttributes = FontAttributes.Bold,
            TextColor = Color.Black,
            VerticalOptions = new LayoutOptions(LayoutAlignment.Center, true),
            HorizontalOptions = new LayoutOptions(LayoutAlignment.Center, true)
        };

        placeholderGrid.Children.Add(placeHolderText);

        this.Content = placeholderGrid;
    }

}

在你的Android -> Resources -> create a folder called 'layout' -> native_ad.xml中添加下面的xml

 <?xml version="1.0" encoding="UTF-8" ?>
    <com.google.android.gms.ads.nativead.NativeAdView 
    android:hardwareAccelerated="false"
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

  <android.support.v7.widget.CardView
        xmlns:app="http://schemas.android.com/apk/res-auto"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:cardPreventCornerOverlap="false"
        app:cardCornerRadius="12dp">
 
        <LinearLayout
            xmlns:android="http://schemas.android.com/apk/res/android"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:orientation="vertical"
            android:background="#FFFFFF">
 
            <AbsoluteLayout
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:layout_weight="1">
 
                <com.google.android.gms.ads.nativead.MediaView
                  android:layout_width="match_parent"
                 android:layout_height="match_parent"
                    android:id="@+id/ad_media"/>
                
 
                <TextView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:gravity="left"
                    android:text="Ad"
                    android:textColor="#FFFFFF"
                    android:background="#FFCC66"
                    android:textSize="14sp"
                    android:padding="4dp" />
            </AbsoluteLayout>
 
            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:orientation="horizontal"
                android:padding="5dp">
 
                <LinearLayout
                    android:layout_height="wrap_content"
                    android:layout_width="match_parent"
                    android:layout_weight="1"
                    android:orientation="vertical"
                    android:gravity="fill_horizontal">
 
                    <LinearLayout
                        android:layout_height="wrap_content"
                        android:layout_width="wrap_content"
                        android:orientation="horizontal">
 
                        <ImageView
                            android:id="@+id/ad_app_icon"
                            android:layout_width="40dp"
                            android:layout_height="40dp"
                            android:adjustViewBounds="true"
                            android:paddingBottom="5dp"
                            android:paddingEnd="5dp"
                            android:paddingRight="5dp"/>
 
                        <LinearLayout
                            android:layout_width="match_parent"
                            android:layout_height="wrap_content"
                            android:orientation="vertical">
 
                            <TextView
                                android:id="@+id/ad_headline"
                                android:layout_width="match_parent"
                                android:layout_height="wrap_content"
                                android:textColor="#0000FF"
                                android:text="Join the dark side!"
                                android:textSize="16sp"
                                android:textStyle="bold" />
 
                            <LinearLayout
                                android:layout_width="match_parent"
                                android:layout_height="wrap_content"
                                android:orientation="horizontal">
 
                                <TextView
                                    android:id="@+id/ad_advertiser"
                                    android:layout_width="wrap_content"
                                    android:layout_height="wrap_content"
                                    android:gravity="bottom"
                                    android:textSize="14sp"
                                    android:text="Google"
                                    android:textColor="#222222"
                                    android:textStyle="bold"/>
 
                                <RatingBar
                                    android:id="@+id/ad_stars"
                                    style="?android:attr/ratingBarStyleSmall"
                                    android:layout_width="wrap_content"
                                    android:layout_height="wrap_content"
                                    android:isIndicator="true"
                                    android:numStars="5"
                                    android:stepSize="0.5"
                                    android:rating="4" />
                            </LinearLayout>
 
                        </LinearLayout>
                    </LinearLayout>
 
                    <TextView
                        android:textColor="#555555"
                        android:id="@+id/ad_body"
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        android:text="Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nis."
                        android:textSize="12sp" />
                </LinearLayout>
 
                <LinearLayout
                    android:layout_height="wrap_content"
                    android:layout_width="wrap_content"
                    android:orientation="vertical"
                    android:layout_gravity="center_vertical"
                    android:paddingLeft="5dp">

                    <TextView
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:layout_gravity="center_horizontal"
                        android:id="@+id/ad_store"
                           android:text="Google Play"
                        android:textColor="#222222"
                         android:textSize="12sp" />
 
                    <Button
                        android:id="@+id/ad_call_to_action"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:gravity="center"
                        android:layout_margin="0dp"
                        android:text="INSTALL"
                        android:textSize="12sp" />
 
                    <TextView
                        android:id="@+id/ad_price"
                        android:text="$ 3.49"
                        android:textColor="#222222"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:layout_gravity="center_horizontal"
                        android:textSize="12sp" />
 
                </LinearLayout>
            </LinearLayout>
        </LinearLayout>
    </android.support.v7.widget.CardView>

</com.google.android.gms.ads.nativead.NativeAdView>

在您的特定 Android 中添加以下源代码,

using System;
using Android.Content;
using Android.Gms.Ads;
using Android.Gms.Ads.NativeAd;
using Android.Views;
using Android.Widget;
using Xamarin.Forms;
using Xamarin.Forms.Platform.Android;

[assembly: ExportRenderer(typeof(xxxx.Common.AdsView.NativeAdView), typeof(xxxx.Droid.Helpers.AdsView.NativeAd))]
namespace xxxx.Droid.Helpers.AdsView
{
    public class NativeAd : ViewRenderer
    {

        public NativeAd(Context context) : base(context) { }
        protected override void OnElementChanged(ElementChangedEventArgs<Xamarin.Forms.View> e)
        {
            base.OnElementChanged(e);

            if (Control == null)
            {
                var adLoader = new AdLoader.Builder(Context, "ca-app-pub-3940256099942544/2247696110");

                var listener = new NativeAdLoadedListener();
                listener.OnNativeAdLoaded += (s, ad) =>
                {
                    try
                    {
                        var root = new NativeAdView(Context);
                        var inflater = (LayoutInflater)Context.GetSystemService(Context.LayoutInflaterService);
                        var adView = (NativeAdView)inflater.Inflate(Resource.Layout.native_ad, root);

                        populateUnifiedNativeAdView(ad, adView);

                        SetNativeControl(adView);
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine(ex.Message);
                    }
                };

                adLoader.ForNativeAd(listener);
                var requestBuilder = new AdRequest.Builder();
                adLoader.Build().LoadAd(requestBuilder.Build());
            }
        }

        private void populateUnifiedNativeAdView(Android.Gms.Ads.NativeAd.NativeAd nativeAd, NativeAdView adView)
        {
            adView.MediaView = adView.FindViewById<MediaView>(Resource.Id.ad_media);

            // Set other ad assets.
            adView.HeadlineView = adView.FindViewById<TextView>(Resource.Id.ad_headline);
            adView.BodyView = adView.FindViewById<TextView>(Resource.Id.ad_body);
            adView.CallToActionView = adView.FindViewById<TextView>(Resource.Id.ad_call_to_action);
            adView.IconView = adView.FindViewById<ImageView>(Resource.Id.ad_app_icon);
            adView.PriceView = adView.FindViewById<TextView>(Resource.Id.ad_price);
            adView.StarRatingView = adView.FindViewById<RatingBar>(Resource.Id.ad_stars);
            adView.StoreView = adView.FindViewById<TextView>(Resource.Id.ad_store);
            adView.AdvertiserView = adView.FindViewById<TextView>(Resource.Id.ad_advertiser);

            // The headline and mediaContent are guaranteed to be in every UnifiedNativeAd.
            ((TextView)adView.HeadlineView).Text = nativeAd.Headline;

            // These assets aren't guaranteed to be in every UnifiedNativeAd, so it's important to
            // check before trying to display them.
            if (nativeAd.Body == null)
            {
                adView.BodyView.Visibility = ViewStates.Invisible;
            }
            else
            {
                adView.BodyView.Visibility = ViewStates.Visible;
                ((TextView)adView.BodyView).Text = nativeAd.Body;
            }

            if (nativeAd.CallToAction == null)
            {
                adView.CallToActionView.Visibility = ViewStates.Invisible;
            }
            else
            {
                adView.CallToActionView.Visibility = ViewStates.Visible;
                ((Android.Widget.Button)adView.CallToActionView).Text = nativeAd.CallToAction;
            }

            if (nativeAd.Icon == null)
            {
                adView.IconView.Visibility = ViewStates.Gone;
            }
            else
            {
                ((ImageView)adView.IconView).SetImageDrawable(nativeAd.Icon.Drawable);
                adView.IconView.Visibility = ViewStates.Visible;
            }

            if (string.IsNullOrEmpty(nativeAd.Price))
            {
                adView.PriceView.Visibility = ViewStates.Gone;
            }
            else
            {
                adView.PriceView.Visibility = ViewStates.Visible;
                ((TextView)adView.PriceView).Text = nativeAd.Price;
            }

            if (nativeAd.Store == null)
            {
                adView.StoreView.Visibility = ViewStates.Invisible;
            }
            else
            {
                adView.StoreView.Visibility = ViewStates.Visible;
                ((TextView)adView.StoreView).Text = nativeAd.Store;
            }

            if (nativeAd.StarRating == null)
            {
                adView.StarRatingView.Visibility = ViewStates.Invisible;
            }
            else
            {
                ((RatingBar)adView.StarRatingView).Rating = nativeAd.StarRating.FloatValue();
                adView.StarRatingView.Visibility = ViewStates.Visible;
            }

            if (nativeAd.Advertiser == null)
            {
                adView.AdvertiserView.Visibility = ViewStates.Invisible;
            }
            else
            {
                ((TextView)adView.AdvertiserView).Text = nativeAd.Advertiser;
                adView.AdvertiserView.Visibility = ViewStates.Visible;
            }

            // This method tells the Google Mobile Ads SDK that you have finished populating your
            // native ad view with this native ad.
            adView.SetNativeAd(nativeAd);
        }
    }

    public class NativeAdLoadedListener : AdListener, Android.Gms.Ads.NativeAd.NativeAd.IOnNativeAdLoadedListener
    {
        void Android.Gms.Ads.NativeAd.NativeAd.IOnNativeAdLoadedListener.OnNativeAdLoaded(Android.Gms.Ads.NativeAd.NativeAd ad)
        {
            OnNativeAdLoaded?.Invoke(this, ad);
        }

        public EventHandler<Android.Gms.Ads.NativeAd.NativeAd> OnNativeAdLoaded { get; set; }
    }

}

就是这样,现在您可以使用以下代码在您的 xaml 页面上显示原生广告。

<ContentViews1:NativeAdView HeightRequest="100" />

【讨论】:

    【解决方案2】:

    您也可以在 iOS 中使用GoogleMobileAds。重要的是来自 NuGet 的包 Xamarin.Firebase.iOS.AdMob

    在 AppDelegate.cs 中

    ...
    using Google.MobileAds;
    ...
    
    public override bool FinishedLaunching(UIApplication app, NSDictionary options)
    {
       . . .
       MobileAds.Configure("ca-app-pub-3940256099942544/2247696110 ");
       . . . 
    } 
    

    在 iOS 依赖中

    [assembly: Xamarin.Forms.Dependency(typeof(NativeiOSAd))]
    namespace XXX.iOS
    {
        public class NativeiOSAd:NativeAd
        {
    
            NativeExpressAdView mAdView;
    
            public NativeiOSAd()
            {
            }
    
            public void Show()
            {
                AdSize adSize = new AdSize();
                adSize.Size = new CGSize(UIScreen.MainScreen.Bounds.Size.Width, 100);
    
                mAdView = new NativeExpressAdView(adSize)
                {
                    AdUnitID = "ca-app-pub-3940256099942544/2247696110"
                };
    
                Request request = Request.GetDefaultRequest();
    
    
                mAdView.LoadRequest(request);
            }
        }
    }
    

    不要忘记在应用的 Info.plist 文件中添加 NSAllowsArbitraryLoadsNSAllowsArbitraryLoadsForMediaNSAllowsArbitraryLoadsInWebContent 例外以禁用 ATS 限制。

    【讨论】:

    • 感谢您的回答
    猜你喜欢
    • 2018-01-06
    • 1970-01-01
    • 1970-01-01
    • 2020-12-17
    • 2021-08-01
    • 2016-10-16
    • 2018-05-12
    • 1970-01-01
    • 2021-04-24
    相关资源
    最近更新 更多