Cómo reaccionar al enfoque
Organiza tus páginas con colecciones
Guarda y categoriza el contenido según tus preferencias.
Proporcionar indicadores visuales para facilitar la visualización del enfoque
Si bien todos los elementos enfocables del tema de Material ya tienen un estilo de enfoque
coincide con el tema, quizás debas agregar algunos elementos visuales para que la
el elemento enfocado sea más fácil de detectar. Una buena solución sería cambiar el borde de
tu elemento con un color que tenga un buen contraste con el fondo:
var color by remember { mutableStateOf(Color.White) }
Card(
modifier = Modifier
.onFocusChanged {
color = if (it.isFocused) Red else White
}
.border(5.dp, color)
) {}
En este ejemplo, remember
se usa para almacenar el color del borde de
y el esquema del elemento se actualiza cada vez que este
gana o pierde concentración.
Implementa señales visuales avanzadas
Con Jetpack Compose, también puedes crear imágenes más sofisticadas y avanzadas
que coincidan mejor con tu IU.
- Primero, crea un
IndicationInstance
que dibuje visualmente la indicación que deseas en tu IU:
private class MyHighlightIndicationNode(private val interactionSource: InteractionSource) :
Modifier.Node(), DrawModifierNode {
private var isFocused = false
override fun onAttach() {
coroutineScope.launch {
var focusCount = 0
interactionSource.interactions.collect { interaction ->
when (interaction) {
is FocusInteraction.Focus -> focusCount++
is FocusInteraction.Unfocus -> focusCount--
}
val focused = focusCount > 0
if (isFocused != focused) {
isFocused = focused
invalidateDraw()
}
}
}
}
override fun ContentDrawScope.draw() {
drawContent()
if (isFocused) {
drawRect(size = size, color = Color.White, alpha = 0.2f)
}
}
}
- A continuación, crea un
Indication
y recuerda el estado enfocado:
object MyHighlightIndication : IndicationNodeFactory {
override fun create(interactionSource: InteractionSource): DelegatableNode {
return MyHighlightIndicationNode(interactionSource)
}
override fun hashCode(): Int = -1
override fun equals(other: Any?) = other === this
}
- Agrega
Indication
y InteractionSource
a la IU mediante el modificador indication()
:
var interactionSource = remember { MutableInteractionSource() }
Card(
modifier = Modifier
.clickable(
interactionSource = interactionSource,
indication = MyHighlightIndication,
enabled = true,
onClick = { }
)
) {
Text("hello")
}
Comprende el estado del enfoque
Por lo general, cada vez que cambia un estado de enfoque, se activa un FocusEvent
.
del árbol, y los elementos superiores de un modificador focusable()
pueden escucharlo con el
Modificador onFocusChanged()
.
Si necesitas conocer el estado del enfoque,puedes usar estas APIs junto
con el modificador onFocusChanged
:
isFocused
muestra true
si el elemento componible al que se adjunta el modificador
está enfocado
hasFocus
funciona de manera similar a isFocused
, pero con una diferencia sustancial:
en lugar de comprobar solo la actual, comprueba si el elemento o uno de sus
se concentra
isCaptured
muestra true
cada vez que se mantiene el enfoque. Esto sucede
por ejemplo, cuando un TextField
contiene datos incorrectos, de modo que intentar enfocar
otros elementos no
borrarán el enfoque.
Estos campos se muestran a continuación:
Modifier.onFocusChanged {
val isFocused = it.isFocused
val hasFocus = it.hasFocus
val isCaptured= it.isCaptured
}
Recomendaciones para ti
El contenido y las muestras de código que aparecen en esta página están sujetas a las licencias que se describen en la Licencia de Contenido. Java y OpenJDK son marcas registradas de Oracle o sus afiliados.
Última actualización: 2025-08-23 (UTC)
[[["Fácil de comprender","easyToUnderstand","thumb-up"],["Resolvió mi problema","solvedMyProblem","thumb-up"],["Otro","otherUp","thumb-up"]],[["Falta la información que necesito","missingTheInformationINeed","thumb-down"],["Muy complicado o demasiados pasos","tooComplicatedTooManySteps","thumb-down"],["Desactualizado","outOfDate","thumb-down"],["Problema de traducción","translationIssue","thumb-down"],["Problema con las muestras o los códigos","samplesCodeIssue","thumb-down"],["Otro","otherDown","thumb-down"]],["Última actualización: 2025-08-23 (UTC)"],[],[],null,["# React to focus\n\nProvide visual cues for easier focus visualization\n--------------------------------------------------\n\nWhile all the focusable elements from Material Theme already have a focus style\nthat matches the theme, you might need to add some visual elements to make the\nfocused element easier to spot. A good solution would be to change the border of\nyour element with a color that has a good contrast with the background:\n\n\n```kotlin\nvar color by remember { mutableStateOf(Color.White) }\nCard(\n modifier = Modifier\n .onFocusChanged {\n color = if (it.isFocused) Red else White\n }\n .border(5.dp, color)\n) {}https://github.com/android/snippets/blob/dd30aee903e8c247786c064faab1a9ca8d10b46e/compose/snippets/src/main/java/com/example/compose/snippets/touchinput/focus/FocusSnippets.kt#L427-L434\n```\n\n\u003cbr /\u003e\n\nIn this example, `remember` is used to store the color of the border across\nrecompositions, and the outline of the element is updated every time the element\ngains or loses focus.\n\n### Implement advanced visual cues\n\nWith Jetpack Compose, you can also create more sophisticated and advanced visual\ncues that match better with your UI.\n\n1. First, create an `IndicationInstance` that visually draws the cue you want in your UI: \n\n ```kotlin\n private class MyHighlightIndicationNode(private val interactionSource: InteractionSource) :\n Modifier.Node(), DrawModifierNode {\n private var isFocused = false\n\n override fun onAttach() {\n coroutineScope.launch {\n var focusCount = 0\n interactionSource.interactions.collect { interaction -\u003e\n when (interaction) {\n is FocusInteraction.Focus -\u003e focusCount++\n is FocusInteraction.Unfocus -\u003e focusCount--\n }\n val focused = focusCount \u003e 0\n if (isFocused != focused) {\n isFocused = focused\n invalidateDraw()\n }\n }\n }\n }\n\n override fun ContentDrawScope.draw() {\n drawContent()\n if (isFocused) {\n drawRect(size = size, color = Color.White, alpha = 0.2f)\n }\n }\n }\n https://github.com/android/snippets/blob/dd30aee903e8c247786c064faab1a9ca8d10b46e/compose/snippets/src/main/java/com/example/compose/snippets/touchinput/focus/FocusSnippets.kt#L439-L467\n ```\n2. Next, create an `Indication` and remember the focused state: \n\n ```kotlin\n object MyHighlightIndication : IndicationNodeFactory {\n override fun create(interactionSource: InteractionSource): DelegatableNode {\n return MyHighlightIndicationNode(interactionSource)\n }\n\n override fun hashCode(): Int = -1\n\n override fun equals(other: Any?) = other === this\n }https://github.com/android/snippets/blob/dd30aee903e8c247786c064faab1a9ca8d10b46e/compose/snippets/src/main/java/com/example/compose/snippets/touchinput/focus/FocusSnippets.kt#L471-L479\n ```\n3. Add both the `Indication` and an `InteractionSource` to the UI, via the `indication()` modifier: \n\n ```kotlin\n var interactionSource = remember { MutableInteractionSource() }\n\n Card(\n modifier = Modifier\n .clickable(\n interactionSource = interactionSource,\n indication = MyHighlightIndication,\n enabled = true,\n onClick = { }\n )\n ) {\n Text(\"hello\")\n }https://github.com/android/snippets/blob/dd30aee903e8c247786c064faab1a9ca8d10b46e/compose/snippets/src/main/java/com/example/compose/snippets/touchinput/focus/FocusSnippets.kt#L485-L497\n ```\n\nUnderstand the state of the focus\n---------------------------------\n\nGenerally, every time a state of the focus changes, a `FocusEvent` is fired up\nthe tree, and the parents of a `focusable()` modifier can listen to it using the\n`onFocusChanged()` modifier.\n\nIf you need to know the state of the focus,you can use these APIs in conjunction\nwith the `onFocusChanged` modifier:\n\n- `isFocused` returns `true` if the composable to which the modifier is attached is focused\n- `hasFocus` works similarly to `isFocused`, but with a substantial difference: rather than checking only the current, it checks if the element or one of its children is focused\n- `isCaptured` returns `true` whenever the focus is held. This happens, for instance, when a `TextField` contains incorrect data, so that trying to focus other elements will not clear the focus.\n\nThese fields are shown below: \n\n Modifier.onFocusChanged {\n val isFocused = it.isFocused\n val hasFocus = it.hasFocus\n val isCaptured= it.isCaptured\n }\n\nRecommended for you\n-------------------\n\n- Note: link text is displayed when JavaScript is off\n- [Change focus behavior](/develop/ui/compose/touch-input/focus/change-focus-behavior)\n- [Material Design 2 in Compose](/develop/ui/compose/designsystems/material)\n- [Handle user input](/develop/ui/compose/text/user-input)"]]