super.onCreate(savedInstanceState)
setContent {
ParentLayout(
Modifier
.size(100.dp)
.padding(10.dp)
.background(Color.Blue)
) {
ChildLayout {
Box {}
}
ChildLayout {}
}
}
}
}
本次探索希望能回答下面几个问题
-
ParentLayout 中 通过 modifier 设置大小是如何起到作用的 ?
-
MeasurePolicy 接口的 measure 方法是怎么调用的?他的参数值是怎么来的呢?
-
布局中的测量流程是什么样的?
下面就带着上面这些问题,在看源码的过程中尝试去解释这些问题。
本文源码对应版本 compose_version = ‘1.0.0-rc01’
为了方便跟踪代码,我来给代码设置点跟踪器 (别搞丢了)😜 下面的代码中 modifier 参数达到的位置我会用📍 标记, measurePolicy 到达的位置用 📌 标记
Layout.kt → Layout 函数源码
@Composable inline fun Layout(
content: @Composable () -> Unit,
modifier: Modifier = Modifier,
measurePolicy: MeasurePolicy
) {
val density = LocalDensity.current
val layoutDirection = LocalLayoutDirection.current
ReusableComposeNode<ComposeUiNode, Applier>(
factory = ComposeUiNode.Constructor,
update = {
set(measurePolicy, ComposeUiNode.SetMeasurePolicy) // 👈 📌 measurePolicy 在这
set(density, ComposeUiNode.SetDensity)
set(layoutDirection, ComposeUiNode.SetLayoutDirection)
},
skippableUpdate = materializerOf(modifier), // 👈 📍 modifier 在这
content = content
)
}
从上面源码可以看出,Layout 函数体中没有做什么处理,核心内容就是调用 ReusableComposeNode 函数。
@Composable 注解的函数建议首字母大写已区分普通函数,看代码的时候总觉的 ReusableComposeNode 是个类,点进去发现它是个 Composable 函数 😂 。
Composables.kt → ReusableComposeNode 函数
inline fun <T, reified E : Applier<*>> ReusableComposeNode(
noinline factory: () -> T,
update: @DisallowComposableCalls Updater.() -> Unit,
noinline skippableUpdate: @Composable SkippableUpdater.() -> Unit,
content: @Composable () -> Unit
) {
if (currentComposer.applier !is E) invalidApplier()
currentComposer.startNode()
if (currentComposer.inserting) {
currentComposer.createNode(factory)
} else {
currentComposer.useNode()
}
//执行update函数
Updater(currentComposer).update() // 👈 📌 measurePolicy 在这
//执行skippableUpdate函数
SkippableUpdater(currentComposer).skippableUpdate() // 👈 📍 modifier 在这函数中
currentComposer.startReplaceableGroup(0x7ab4aae9)
content()<