フォーカスをキャプチャして解放する

特殊なインタラクション モード(埋め込みの描画キャンバス、ゲーム コントローラのサーフェス、モーダル入力ダイアログなど)では、アプリがフォーカスを単一のコンポーネントに一時的にロックし、Tab キーや方向キーによる移動を禁止する必要がある場合があります。

キャプチャのフォーカス

フォーカスを取得するには、FocusRequester で captureFocus() を呼び出します。

val focusRequester = remember { FocusRequester() }

Box(
    modifier = Modifier
        .focusRequester(focusRequester)
        .focusable()
        .onFocusChanged { focusState ->
            if (focusState.isFocused) {
                focusRequester.captureFocus()
            }
        }
)

フォーカスがキャプチャされている間、標準のフォーカス ナビゲーション キー(Tab など)では、フォーカスを隣接するコンポーネントに移動できません。

リリースの重点

キャプチャされた状態を終了し、UI 全体で通常のフォーカス ナビゲーションを復元するには、freeFocus() を呼び出します。

IconButton(
    onClick = {
        focusRequester.freeFocus()
    }
) {
    Icon(Icons.Default.Close, contentDescription = "Exit focus lock")
}