添加AdMob的Native广告

1.需要 AdMob账号,一个APP还有一个native广告账号,没有可以使用(

ca-app-pub-3940256099942544/2247696110

2.在需要展示广告的Activity里初始化下载这组代码

MobileAds.initialize(this){}
        adLoader = AdLoader.Builder(this, "ca-app-pub-3940256099942544/2247696110")
            .forUnifiedNativeAd {
                //Show the ad.
                val style = NativeTemplateStyle.Builder().build()
                val template = binding.myTemplate
                template.setStyles(style)
                template.setNativeAd(it)

                if (adLoader.isLoading) {
                    // The AdLoader is still loading ads.
                    // Expect more adLoaded or onAdFailedToLoad callbacks.
                } else {
                    // The AdLoader has finished loading ads.

                    Log.i("forUnifiedNativeAd","success")
                }
            }
            .withAdListener(object : AdListener() {
                override fun onAdFailedToLoad(errorCode: Int) {
                    // Handle the failure by logging, altering the UI, and so on.
                }
            })
            .withNativeAdOptions(NativeAdOptions.Builder().build())
            .build()
        adLoader.loadAds(AdRequest.Builder().build(),5)
//        adLoader.loadAd(AdRequest.Builder().build())

3.其中绑定的元素binding.myTemplate的布局如下:

<com.google.android.ads.nativetemplates.TemplateView
        android:id="@+id/my_template"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        app:gnt_template_type="@layout/gnt_medium_template_view"></com.google.android.ads.nativetemplates.TemplateView>

4.其中“com.google.android.ads.nativetemplates.TemplateView”这个布局引用来自一个模板项目,

地址是:https://github.com/googleads/googleads-mobile-android-native-templates.git

下载下来并且import module到自己的项目,注意修改module的gradle文件的compileSdkVersion和targetSdkVersion和自己项目的版本一致。

5.以上参考来自

https://developers.google.com/admob/android/native/start

https://developers.google.com/admob/android/native/templates

原文地址:https://www.cnblogs.com/xixiaohui/p/12809298.html