Реагировать на фокусировку
Оптимизируйте свои подборки
Сохраняйте и классифицируйте контент в соответствии со своими настройками.
Предоставляйте визуальные подсказки для облегчения визуализации фокуса.
Хотя все фокусируемые элементы из Material Theme уже имеют стиль фокуса, соответствующий теме, вам может потребоваться добавить некоторые визуальные элементы, чтобы элемент, находящийся в фокусе, было легче обнаружить. Хорошим решением было бы изменить границу вашего элемента на цвет, который хорошо контрастирует с фоном:
var color by remember { mutableStateOf(Color.White) }
Card(
modifier = Modifier
.onFocusChanged {
color = if (it.isFocused) Red else White
}
.border(5.dp, color)
) {}
В этом примере remember
используется для сохранения цвета границы при рекомпозиции, а контур элемента обновляется каждый раз, когда элемент получает или теряет фокус.
Внедряйте расширенные визуальные подсказки
С помощью Jetpack Compose вы также можете создавать более сложные и продвинутые визуальные подсказки, которые лучше соответствуют вашему пользовательскому интерфейсу.
- Сначала создайте
IndicationInstance
, который визуально отображает нужный вам сигнал в вашем пользовательском интерфейсе: 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)
}
}
}
- Затем создайте
Indication
и запомните состояние фокусировки: object MyHighlightIndication : IndicationNodeFactory {
override fun create(interactionSource: InteractionSource): DelegatableNode {
return MyHighlightIndicationNode(interactionSource)
}
override fun hashCode(): Int = -1
override fun equals(other: Any?) = other === this
}
- Добавьте в пользовательский интерфейс
Indication
и InteractionSource
с помощью indication()
: var interactionSource = remember { MutableInteractionSource() }
Card(
modifier = Modifier
.clickable(
interactionSource = interactionSource,
indication = MyHighlightIndication,
enabled = true,
onClick = { }
)
) {
Text("hello")
}
Понять состояние фокуса
Как правило, каждый раз, когда состояние фокуса изменяется, FocusEvent
запускается вверх по дереву, и родители модификатора focusable()
могут прослушивать его с помощью модификатора onFocusChanged()
.
Если вам нужно узнать состояние фокуса, вы можете использовать эти API в сочетании с модификатором onFocusChanged
:
-
isFocused
возвращает true
, если составной объект, к которому прикреплен модификатор, находится в фокусе. -
hasFocus
работает аналогично isFocused
, но с существенным отличием: вместо проверки только текущего элемента он проверяет, сфокусирован ли элемент или один из его дочерних элементов. -
isCaptured
возвращает true
всякий раз, когда фокус удерживается. Это происходит, например, когда TextField
содержит неправильные данные, поэтому попытка сфокусировать другие элементы не приведет к очистке фокуса.
Эти поля показаны ниже:
Modifier.onFocusChanged {
val isFocused = it.isFocused
val hasFocus = it.hasFocus
val isCaptured= it.isCaptured
}
{% дословно %}
{% дословно %} Рекомендуется для вас
{% дословно %} {% дословно %}
Контент и образцы кода на этой странице предоставлены по лицензиям. Java и OpenJDK – это зарегистрированные товарные знаки корпорации Oracle и ее аффилированных лиц.
Последнее обновление: 2025-08-23 UTC.
[[["Прост для понимания","easyToUnderstand","thumb-up"],["Помог мне решить мою проблему","solvedMyProblem","thumb-up"],["Другое","otherUp","thumb-up"]],[["Отсутствует нужная мне информация","missingTheInformationINeed","thumb-down"],["Слишком сложен/слишком много шагов","tooComplicatedTooManySteps","thumb-down"],["Устарел","outOfDate","thumb-down"],["Проблема с переводом текста","translationIssue","thumb-down"],["Проблемы образцов/кода","samplesCodeIssue","thumb-down"],["Другое","otherDown","thumb-down"]],["Последнее обновление: 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)"]]