In my current project utilizing Jetpack Compose, I'm tasked with enabling users to input data while also providing functionality to style text with options like bold or italic upon clicking buttons. Given my novice level in Jetpack Compose, I'm seeking guidance on how to implement this feature effectively.
@Composable
fun CustomTextField() {
var isBold by remember { mutableStateOf(false) }
val textState = remember { mutableStateOf(TextFieldValue()) }
val prevPos by remember { mutableStateOf(0) }
Column() {
Button(onClick = {
isBold = !isBold
}) {
Text(text = "Toggle Bold")
}
TextField(
value = textState.value,
onValueChange = {
if (isBold) {
val annotatedString = buildAnnotatedString {
append(it.text)
addStyle(
SpanStyle(fontWeight = FontWeight.Bold),
prevPos,
it.text.length
)
}
textState.value = it.copy(annotatedString, it.selection, it.composition)
} else {
textState.value = it
}
},
textStyle = TextStyle(
fontSize = 16.sp,
lineHeight = 24.sp,
color = Color.Black
),
modifier = Modifier
.padding(16.dp)
.clip(MaterialTheme.shapes.medium)
.background(MaterialTheme.colors.surface)
)
}
}
I am trying through this but my whole text get bold after click on button
Base on the context which you provide.. I think this is better solution from what you have.
Note: I am using Material3
Here is the code:
Here is render result: