我正在使用原生广告 - 华为文档在 Android 中实现原生广告。当我遇到根据屏幕尺寸(0 dp)更改MediaView的高度时,我发现它无法更改。
即使我已经实现了 setOnHierarchyChangeListener,但它也不起作用。以下是我目前取得的成绩。
文件native_ad.xml
<com.huawei.hms.ads.nativead.NativeView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="@+id/native_video_view"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_centerInParent="true"
android:background="#FFFFFF"
android:orientation="vertical">
<androidx.constraintlayout.widget.ConstraintLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<androidx.constraintlayout.widget.ConstraintLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<com.huawei.hms.ads.nativead.MediaView
android:id="@+id/ad_media"
android:layout_width="0dp"
android:layout_height="0dp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHeight_percent="0.8"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintBottom_toTopOf="@id/constraintLayout"/>
<androidx.constraintlayout.widget.ConstraintLayout
android:id="@+id/constraintLayout"
android:layout_width="0dp"
android:layout_height="0dp"
app:layout_constraintHeight_percent="0.2"
android:background="@drawable/white_bg"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@id/ad_media">
<TextView
... />
<TextView
... />
<TextView
.. />
<Button
... />
</androidx.constraintlayout.widget.ConstraintLayout>
</androidx.constraintlayout.widget.ConstraintLayout>
</com.huawei.hms.ads.nativead.NativeView>
功能inItNativeAdView
private fun initNativeAdView(nativeAd: NativeAd?, nativeView: NativeView) {
nativeView.titleView = nativeView.findViewById(R.id.ad_title)
(nativeView.titleView as TextView).text = nativeAd!!.title
nativeView.mediaView = nativeView.findViewById(R.id.ad_media)
nativeView.mediaView.setMediaContent(nativeAd.mediaContent)
nativeView.mediaView.setOnHierarchyChangeListener(object : OnHierarchyChangeListener {
override fun onChildViewAdded(parent: View, child: View) {
*//* if (child is ImageView) {
val imageView: ImageView = child as ImageView
imageView.adjustViewBounds = true
}*//*
val scale = context.resources.displayMetrics.density
val maxHeightPixels = 175
val maxHeightDp = (maxHeightPixels * scale + 0.5f).toInt()
if (child is ImageView) { //Images
val imageView = child
imageView.adjustViewBounds = true
imageView.maxHeight = maxHeightDp
} else { //Videos
val params = child.layoutParams
params.height = maxHeightDp
child.layoutParams = params
}
}
override fun onChildViewRemoved(parent: View, child: View) {}
})
}
setOnHierarchyChangeListener 的实现不会改变 mediaView 的高度。
目前我正在查看原生广告如下:
我希望动态 mediaView 会出现这样的情况:
我怎样才能解决这个问题?