Kotlin:未调用 onGlobalLayout
Kotlin: onGlobalLayout not being called
我正在使用 Kotlin,并使用 onGlobalLayout 加载图像视图。通过 loadUrl。在不使用 afterMeasured 的情况下,我的图像加载得很好,但有时由于高度为 0,它会崩溃。所以我正在考虑使用我在扩展函数 afterMeasured 中定义的 onGlobalLayout,如下所示。然而,不知何故 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 的方式不正确?
首先,您应该比较 width
和 height
而不是 measuredWidth
和 measuredHeight
。后一个尺寸仅在 measure/layout 过程中使用。
其次,您应该确保 ImageView
在布局中得到正确描述。那就是它的layout_width
和layout_height
一定不能是wrap_content
。此外,其他视图不得导致此 ImageView
具有 0
大小。
我正在使用 Kotlin,并使用 onGlobalLayout 加载图像视图。通过 loadUrl。在不使用 afterMeasured 的情况下,我的图像加载得很好,但有时由于高度为 0,它会崩溃。所以我正在考虑使用我在扩展函数 afterMeasured 中定义的 onGlobalLayout,如下所示。然而,不知何故 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 的方式不正确?
首先,您应该比较 width
和 height
而不是 measuredWidth
和 measuredHeight
。后一个尺寸仅在 measure/layout 过程中使用。
其次,您应该确保 ImageView
在布局中得到正确描述。那就是它的layout_width
和layout_height
一定不能是wrap_content
。此外,其他视图不得导致此 ImageView
具有 0
大小。