当前代码
@Composable
fun TextDemo() {
var selectedIndex by remember {
mutableIntStateOf(0)
}
Row {
TabText(
text = "First",
isSelected = selectedIndex == 0,
onClick = {
selectedIndex = 0
},
)
TabText(
text = "Second",
isSelected = selectedIndex == 1,
onClick = {
selectedIndex = 1
},
)
}
}
@Composable
fun TabText(
text: String,
isSelected: Boolean,
onClick: () -> Unit,
) {
val tabTextColor by animateColorAsState(
targetValue = if (isSelected) {
Color.Red
} else {
Color.Black
},
animationSpec = tween(
easing = LinearEasing,
),
label = "tab_text_color",
)
Text(
modifier = Modifier
.padding(8.dp)
.clickable {
onClick()
},
text = text,
color = tabTextColor,
)
}
用户界面可供参考
Row
中的两个Text
版面判断器重组
Question个
How to reduce the recompositions when text color changes?个
对于alpha
、transition
等属性,可以在使用Modifier.graphicsLayer {}
设置动画时避免重新组合
具有alpha
个动画而不是 colored颜色 的相同代码在每次 Select 更改时仅重组一次.
代码
@Composable
fun TabText(
text: String,
isSelected: Boolean,
onClick: () -> Unit,
) {
val alphaValue by animateFloatAsState(
targetValue = if (isSelected) {
1F
} else {
0.5F
},
animationSpec = tween(
easing = LinearEasing,
),
label = "tab_text_color",
)
Text(
modifier = Modifier
.graphicsLayer {
alpha = alphaValue
}
.padding(8.dp)
.clickable {
onClick()
},
text = text,
)
}