xamarin.forms - Xamarin.Forms Google 服务 AdMob
问题描述
我正在尝试在我的 Xamarin.Forms 应用程序(目前为 Android 版本)中实现 AdMob。这是我到目前为止所做的:
- 在我的共享项目中创建了一个自定义控件 AdViewControl:
public class AdControlView : Xamarin.Forms.View
{
}
- 在显示广告的页面中,我在 xaml 中添加了自定义控件:
xmlns:ads="clr-namespace:MyFeelingBuddyTwo.Views"
<ads:AdControlView BackgroundColor="Red"/>
- 在 Android 项目 (AndroidManifest.xml) 中,在:
<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"/>
- 在 Android 项目中,我仍然创建了一个 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);
}
}
}
}
- 在 MainActivity 中,在加载应用程序之前初始化 MobileAds:
MobileAds.Initialize(ApplicationContext, "ca-app-pub-appid");
当我运行时,我得到红色背景,但没有加载任何广告。有任何想法吗?
解决方案
在 AdControlView 类中,我添加了:
public static readonly BindableProperty AdUnitIdProperty = BindableProperty.Create("AdUnitId", typeof(string), typeof(AdControlView));
public string AdUnitId
{
get { return (string)GetValue(AdUnitIdProperty); }
set { SetValue(AdUnitIdProperty, value); }
}
现在我可以在横幅占位符中看到“测试广告”。
推荐阅读
- woocommerce - Woocommerce:将属性值附加到订单注释
- c# - 我的 PDM 插件中的 C# Getthumbnail2 方法问题
- steam - Steam API - 获取 CSGO 存储单元的内容
- holtwinters - 霍尔特冬天阿尔法
- android - 我的 Android 应用程序版本超出预期
- django - 西里尔字母变成了问号 | Django 模板 HTML 元标记
- python - OSError: [WinError 126] 在 pyinstaller 中找不到指定的模块
- json - Swift : Codable Struct Always Nil
- javascript - 有没有更好的方法来遍历 React 渲染部分中的数据?
- php - 使用 PHP 在 MySQL 中插入多行