視覚的な手がかりを提供して、焦点をわかりやすく可視化する
マテリアル テーマのフォーカス可能なすべての要素にはすでにフォーカス スタイルがありますが、 使用する場合は、視覚要素を追加して 要素を特定しやすくなります。良い解決策は、境界線を 要素は、背景とのコントラストがはっきりした色で使用してください。
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 では、より洗練された高度なビジュアル コンテンツも UI に合わせたキューを作成できます。
- まず、UI に必要なキューを視覚的に描画する
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()
修飾子を使用して、Indication
とInteractionSource
の両方を UI に追加します。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
}
現在、おすすめはありません。
Google アカウントにログインしてください。