我需要根据FrameLayout android:id="@+id/heart_strength
的height
of FrameLayout android:id="@+id/heart_strength_background
来设置FrameLayout android:id="@+id/heart_strength_background
的高度,其高度设置如下:
<FrameLayout
android:id="@+id/cardiogram_background_light"
android:layout_width="0dp"
android:layout_height="0dp"
android:layout_marginStart="@dimen/default_screen_margin"
android:layout_marginTop="@dimen/chart_widget_margin_top"
android:layout_marginEnd="@dimen/default_screen_margin"
android:background="@drawable/chart_widget_background_light_gray"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHeight_percent="0.184"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/heart_rate_diagram_background_light" />
<FrameLayout
android:id="@+id/heart_strength_background"
android:layout_width="@dimen/cardiogram_status_bar_width"
android:layout_height="0dp"
android:layout_marginEnd="@dimen/default_screen_margin"
android:background="@drawable/chart_widget_background_dark_gray"
app:layout_constraintBottom_toBottomOf="@+id/cardiogram_background_light"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintTop_toTopOf="@+id/cardiogram_background_light" >
<FrameLayout
android:id="@+id/heart_strength"
android:layout_width="match_parent"
android:layout_height="0dp"
app:heartStrength="@{viewmodel.heartStrengthLiveData}"
android:background="@drawable/chart_widget_background_light_gray"
android:backgroundTint="@color/turquoise"
android:layout_gravity="bottom"/>
</FrameLayout>
当我试图获得heart_strength.parent
布局的真实高度时:
@JvmStatic
@BindingAdapter("app:heartStrength")
fun setHeartStrengthViewHeight(bar: FrameLayout, level: Int) {
val barParent = bar.parent as FrameLayout
println("bar parent height: ${barParent.layoutParams.height}")
}
我得到了0
。我怎么知道实际高度?
我有一张卡片(cardiogram_background_light)。它的高度以%为单位动态变化。正因为如此,卡中的条形图的最大高度也会动态变化。以前,我将其高度设置为maxHeight * Value /100。但是现在maxHeight在不同屏幕大小上动态变化,我想知道它的值。
发布于 2022-02-12 13:25:15
这是因为在调用setHeartStrengthViewHeight
时还没有绘制视图。要解决这个问题,请尝试以下方法:
@JvmStatic
@BindingAdapter("app:heartStrength")
fun setHeartStrengthViewHeight(bar: FrameLayout, level: Int) {
val barParent = bar.parent as FrameLayout
val observer : ViewTreeObserver = barParent.viewTreeObserver
observer.addOnGlobalLayoutListener(object: ViewTreeObserver.OnGlobalLayoutListener {
override fun onGlobalLayout() {
println("bar parent height: ${barParent.height}")
barParent.viewTreeObserver.removeOnGlobalLayoutListener(this)
}
})
}
https://stackoverflow.com/questions/71091664
复制相似问题