我正在try 使用XML格式显示AdMob原生广告,并在Jetpack Compose中使用androidViewBinding.广告根本没有显示,但我没有收到任何有用的错误消息.
在onAdFailedToLoad
以内,我只得到"内部错误."例外.
对于xml本身,当我验证文件时,我得到"错误:(5,42)cvc-elt.1.a:找不到元素‘com.google.android.gms.ads.nativead.NativeAdView’."的声明.
我在build.gradle文件中启用了viewBinding.已添加所有必要的依赖项.
这是可组合函数:
@Composable
fun NativeAdView(adUnitId: String) {
Box(modifier = Modifier.defaultMinSize(minHeight = 200.dp)) {
AndroidViewBinding(
factory = { inflater, parent, attachToParent ->
val binding = NativeAdViewBinding.inflate(inflater, parent, attachToParent)
val adView = binding.root.also { adView ->
adView.headlineView = binding.adHeadline
adView.iconView = binding.adAppIcon
}
try {
val adLoader = AdLoader.Builder(
adView.context,
adUnitId,
)
.forNativeAd { nativeAd ->
nativeAd.icon?.let {
binding.adAppIcon.setImageDrawable(it.drawable)
binding.adAppIcon.isVisible = true
}
nativeAd.headline?.let {
if (it.isNotBlank()) {
binding.adHeadline.text = it
binding.adHeadline.isVisible = true
}
}
adView.setNativeAd(nativeAd)
}
.withAdListener(
object : AdListener() {
override fun onAdFailedToLoad(error: LoadAdError) {
super.onAdFailedToLoad(error)
}
},
)
.withNativeAdOptions(NativeAdOptions.Builder().build())
.build()
adLoader.loadAd(AdRequest.Builder().build())
} catch (e: Exception) {
Log.e("Exception", e.message.toString())
}
binding
},
)
}
}
这是UI:
<?xml version="1.0" encoding="utf-8"?>
<com.google.android.gms.ads.nativead.NativeAdView
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="test ad" />
<ImageView
android:id="@+id/ad_app_icon"
android:layout_width="52dp"
android:layout_height="52dp"
android:adjustViewBounds="true"
android:contentDescription="ad_icon" />
<TextView
android:id="@+id/ad_headline"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textSize="16sp" />
</LinearLayout>
</com.google.android.gms.ads.nativead.NativeAdView>