Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to manage Focus state in Jetpack's Compose

I have a custom composable View (Surface + Text essentially) and I want to change the color of the surface depending on the focus state. The FocusManager#FocusNode is marked internal and I am unaware of any way to achieve this. Is this simply just not available yet? Any one else have to tackle this?

like image 396
Maurycy Avatar asked Apr 23 '20 18:04

Maurycy


People also ask

How do you prevent unnecessary Recompositions in Jetpack Compose?

The solution here is to provide item keys. Providing a stable key for each item lets Compose avoid unnecessary recompositions. In this case, Compose can see that the item now at spot 3 is the same item that used to be at spot 2. Since none of the data for that item has changed, Compose doesn't have to recompose it.

What is state hoisting in Jetpack Compose?

State hoisting in Compose is a pattern of moving state to a composable's caller to make a composable stateless. The general pattern for state hoisting in Jetpack Compose is to replace the state variable with two parameters: value: T : the current value to display.

Which keyboard action property is used to move the focus to the next composable?

Flutter: keyboard actions and next focus field.


1 Answers

With 1.0.x you can use the Modifier.onFocusChanged to observe focus state events.
Something like:

var color by remember { mutableStateOf(Black) }
val focusRequester = FocusRequester()

Text(
    modifier = Modifier
        .focusRequester(focusRequester)
        .onFocusChanged { color = if (it.isFocused) Green else Black }
        .focusModifier()
        .pointerInput(Unit) { detectTapGestures { focusRequester.requestFocus() } },
    text = "Text",
    color = color
)
like image 193
Gabriele Mariotti Avatar answered Nov 26 '22 03:11

Gabriele Mariotti