【问题标题】:Adding an ad to a Fragment (KOTLIN)将广告添加到片段 (KOTLIN)
【发布时间】:2021-11-04 17:51:41
【问题描述】:

希望到目前为止您过得愉快!我正在尝试向我的片段添加和广告,但是当我运行程序 (KOTLIN) 时它一直没有显示。

这是我的片段 XML(运行测试广告):

    <com.google.android.gms.ads.AdView
    xmlns:ads="http://schemas.android.com/apk/res-auto"
    android:id="@+id/adView"
    android:layout_marginTop="450dp"
    android:elevation="7dp"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    ads:adSize="SMART_BANNER"
    ads:adUnitId="ca-app-pub-3940256099942544/6300978111">

</com.google.android.gms.ads.AdView>

然后我尝试在我的片段中加载它(SettingsFragment.kt):

override fun onCreateView(
    inflater: LayoutInflater, container: ViewGroup?,
    savedInstanceState: Bundle?
): View? {
    // Inflate the layout for this fragment
    _binding = FragmentSettingsBinding.inflate(inflater, container, false)
    val view = binding.root
    return view

    MobileAds.initialize(context)
    val adRequest = AdRequest.Builder().build()
    binding.adView.loadAd(adRequest)
}

我的 Build.gradle 中有这两行:

implementation 'com.google.android.gms:play-services-ads:19.3.0'
implementation 'com.android.support:multidex:1.0.3'

而且我认为我的 android 清单也符合元数据和互联网权限(值已更改)

    <meta-data
    android:name="com.google.android.gms.ads.APPLICATION_ID"
    android:value="ca-app-pub-1234567890123456~1234567890"/>

    <uses-permission android:name="android.permission.INTERNET" />

我一直在搜索,但没有找到任何地方可以帮助我在片段中放置广告。有没有人这样做过/知道怎么做?我是android新手,还不知道该怎么做。非常感谢!

【问题讨论】:

    标签: android android-studio kotlin ads adview


    【解决方案1】:

    我所要做的就是将我创建的移动广告移动到 OnViewCreated() 部分:

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
    
        MobileAds.initialize(context) {}
        mAdView = binding.adView
        val adRequest = AdRequest.Builder().build()
        mAdView.loadAd(adRequest)
    }
    

    非常抱歉浪费了看我问题时间的人们的时间,我非常感谢他们的关心。非常感谢!

    【讨论】:

      猜你喜欢
      • 2021-09-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-11-18
      • 2010-12-07
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多