View.measuredHeight 返回错误值

问题描述 投票:0回答:2

我需要将 TextView 从 0 扩展到它所具有的任何高度,但测量的高度返回错误的值,使用动画它会在下面裁剪一些空间,但只需“View.isVisible = true”它就可以正常工作。

P.S:仅在一行中的大文本上有问题。

这里是展开动画功能:

private fun expand(view: View) {
    view.isVisible = true
    val widthMS = MeasureSpec.makeMeasureSpec(width, MeasureSpec.AT_MOST)
    val heightMS = MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED)
    view.measure(widthMS, heightMS)

    val heightAnimator = ValueAnimator.ofInt(0, view.measuredHeight)
    heightAnimator.interpolator = AccelerateDecelerateInterpolator()
    heightAnimator.addUpdateListener { valueAnimator ->
        val value = valueAnimator.animatedValue as Int
        val layoutParams: ViewGroup.LayoutParams = view.layoutParams
        layoutParams.height = value
        view.layoutParams = layoutParams
    }

    heightAnimator.start()
}
android animation view
2个回答
0
投票

这会起作用。您必须使用

view.measuredHeight
 而不是 
view.height

private fun expand(view: View) {
        view.isVisible = true
        val widthMS = View.MeasureSpec.makeMeasureSpec(width, View.MeasureSpec.AT_MOST)
        val heightMS = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED)
        view.measure(widthMS, heightMS)

        val heightAnimator = ValueAnimator.ofInt(0, view.height)
        heightAnimator.interpolator = AccelerateDecelerateInterpolator()
        heightAnimator.addUpdateListener { valueAnimator ->
            val value = valueAnimator.animatedValue as Int
            val layoutParams: ViewGroup.LayoutParams = view.layoutParams
            layoutParams.height = value
            view.layoutParams = layoutParams
        }

        heightAnimator.start()
    }

0
投票

我也有同样的问题。事实证明宽度的值没有考虑边距。我就是这样解决的

val layoutParams = view.layoutParams as ViewGroup.MarginLayoutParams
val marginStart = layoutParams.marginStart
val marginEnd = layoutParams.marginEnd
val width = parent.width - marginStart - marginEnd
val widthSpec = MeasureSpec.makeMeasureSpec(width, MeasureSpec.EXACTLY)

提供正确的

widthMS
后,
view.measure(widthMS, heightMS)
返回正确的高度值

© www.soinside.com 2019 - 2024. All rights reserved.