Kotlin:onGlobalLayout没有被调用

我正在使用Kotlin,并使用onGlobalLayout来加载图像视图。 通过loadUrl。 没有使用afterMeasured,我的图像加载得很好,但有时由于高度为0,它崩溃。 所以我想使用onGlobalLayout,我在我的扩展功能afterMeasured定义如下。 然而不知何故,onGlobalLayout永远不会被调用。 我的代码有什么问题?

override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_ministry) actionBar?.setDisplayHomeAsUpEnabled(true) model = intent.getSerializableExtra(Constants.ACTIVITY_NAVIGATE_MINISTRY) as Model.Ministries actMinistryImage.loadUrl(model.photo) } fun ImageView.loadUrl(url: String?, placeholder: Int = R.drawable.ministries_blank) { this.afterMeasured { val transformation = FixRatioTransformation(this, true) Picasso.with(context).load(url).error(placeholder).transform(transformation) .placeholder(placeholder).into(this) } } inline fun <T: View> T.afterMeasured(crossinline f: T.() -> Unit) { viewTreeObserver.addOnGlobalLayoutListener(object : ViewTreeObserver.OnGlobalLayoutListener { override fun onGlobalLayout() { if (measuredWidth > 0 && measuredHeight > 0) { viewTreeObserver.removeOnGlobalLayoutListener(this) f() } } }) } 

也许这不是Kotlin特有的,但更多的是调用onGlobalLayout在我身边做得不正确?

首先,你应该比较widthheight而不是measuredWidthmeasuredHeight 。 后者的大小只在度量/布局过程中使用。

其次,您应该确保ImageView在布局中正确描述。 这是它的layout_widthlayout_height不能是wrap_content 。 此外,其他视图不得导致此ImageView具有0大小。