what's the best way to preview a focused state for...
# compose
s
what's the best way to preview a focused state for a button composable?
l
Essentially you want to pass the button an InteractionSource that contains
FocusInteraction.Focus
as its latest interaction There’s a few ways you can do this, either just create a MutableInteractionSource() and emit that interaction, or you can create a fake implementation of InteractionSource that returns a flow that contains that interaction, whatever works for your code base / other usages I guess is fine
s
Much appreciated! Will give it a go
Copy code
class PreviewInteractionSource : MutableInteractionSource {
    override val interactions: Flow<Interaction>
        get() = MutableStateFlow(FocusInteraction.Focus())

    override suspend fun emit(interaction: Interaction) {
        TODO("Not yet implemented")
    }

    override fun tryEmit(interaction: Interaction): Boolean {
        TODO("Not yet implemented")
    }
}

@Composable
@Preview
fun FocusedPrimaryButtonPreview() {
    Button(
        text = "Focused",
        interactionSource = remember {
            PreviewInteractionSource()
        }
    )
}

@Composable
fun Button(
    text: String,
    interactionSource: MutableInteractionSource = remember { MutableInteractionSource() }
) {
    val isFocused = interactionSource.collectIsFocusedAsState().value

    androidx.compose.material3.Button(
        colors = resolveButtonColors(
            isFocused = isFocused,
        ),
        interactionSource = interactionSource,
    ) {
        Text(
            text = text,
            color = if (isFocused) Color.Black else Color.White
        )
    }
}
Hmmm not seeing the expected result w/ this snippet above..
l
Does it work in interactive preview? I don’t think it will work in the static preview because observing interaction source / any animations from the button being in a focused state won’t happen on the first frame
s
Thanks, that makes sense. Interactive preview is working as expected 👌
219 Views