如何创建依赖于其他修饰符值的新修饰符?举个例子,我想让子组件的高度是从父组件传入的高度的一半加上一些常量(因此无法使用 fillMaxHeight(fraction: Float))。
@Composable
fun View() {
MyComposable(modifier = Modifier.size(40.dp))
}
@Composable
fun MyComposable(
modifier: Modifier // Assuming this modifier contains a size
) {
Box(modifier) { // Setting the the size from the passed in modifier
val childHeightModifier = Modifier.height(???) // <-- Wanted to be some specific value depending on parent size
Box(childHeightModifier) {
...
}
}
}
最佳答案
您可以将 BoxWithConstraints
用于此特定用例,它提供父级对其子级施加的约束:
@Composable
fun View() {
MyComposable(modifier = Modifier.size(40.dp))
}
@Composable
fun MyComposable(modifier: Modifier) {
BoxWithConstraints(modifier) { // this: BoxWithConstraintsScope
val childHeightModifier = Modifier.height(maxHeight * 0.5f)
Box(childHeightModifier) {
...
}
}
}
对于Modifier
之间的通信,有一个ModifierLocal
系统in the works ,这将允许做到这一点。
关于android - 修饰符取决于 Jetpack Compose 中其他修饰符的值吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69294900/