우리 앱은 위와 같은 타이틀바가 존재한다.
그러면 그냥 compose에서 제공하는 CenterAlignedTopAppBar
를 사용하면 될 것 같았지만 height를 내가 원하는 대로 조절 할 수가 없어서 따로 만들게 되었다.
@Preview
@Composable
fun TitleBar(
title: String? = "",
leftButton: Painter? = null,
rightButton: Painter? = null,
leftClick: (() -> Unit) = {},
rightClick: (() -> Unit) = {}
) {
Layout({
leftButton?.let {
Box(
Modifier
.layoutId("leftIcon") //아래에서 사용할 아이디
.padding(start = 8.dp)
.clickable { leftClick.invoke() }
) {
Image(
painter = leftButton,
contentDescription = "leftIcon",
modifier = Modifier
.width(44.dp)
.height(44.dp)
)
}
}
title?.let {
Box(
modifier = Modifier
.layoutId("title"),
contentAlignment = Alignment.Center
) {
Text(
text = title,
fontSize = 18.sp,
fontFamily = FontFamily(Font(R.font.nanumsquareotf_acr)),
style = TextStyle(
color = Color.White
),
textAlign = TextAlign.Center,
)
}
}
rightButton?.let {
Box(
Modifier
.layoutId("rightIcon")
.padding(start = 8.dp)
.clickable { rightClick.invoke() }
) {
Image(
painter = rightButton,
contentDescription = "rightIcon",
modifier = Modifier
.width(44.dp)
.height(44.dp)
)
}
}
}, modifier = Modifier
.fillMaxWidth()
.height(44.dp))
{ measurables, constraints ->
val leftIconPlaceable =
measurables.firstOrNull() { it.layoutId == "leftIcon" }
?.measure(constraints.copy(minWidth = 0))
val rightIconPlaceable =
measurables.firstOrNull() { it.layoutId == "rightIcon" }
?.measure(constraints.copy(minWidth = 0))
val maxTitleWidth = if (constraints.maxWidth == Constraints.Infinity) {
constraints.maxWidth
} else {
(constraints.maxWidth - (leftIconPlaceable?.width ?: 0) - (rightIconPlaceable?.width ?: 0))
.coerceAtLeast(0)
}
val titlePlaceable =
measurables.firstOrNull { it.layoutId == "title" }
?.measure(constraints.copy(minWidth = 0, maxWidth = maxTitleWidth))
val layoutHeight = GraphicUtils.convertDpToPixel(44f).roundToInt()
layout(constraints.maxWidth, layoutHeight) {
// left icon
leftIconPlaceable?.placeRelative(
x = 0,
y = (layoutHeight - leftIconPlaceable.height) / 2
)
// Title
titlePlaceable?.placeRelative(
x = ((constraints.maxWidth - titlePlaceable.width) / 2),
y = ((layoutHeight - titlePlaceable.height) / 2)
)
// right icons
rightIconPlaceable?.placeRelative(
x = constraints.maxWidth - rightIconPlaceable.width,
y = (layoutHeight - rightIconPlaceable.height) / 2
)
}
}