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

特殊なインタラクション モード(埋め込み描画キャンバス、ゲーム コントローラ サーフェス、モーダル入力ダイアログなど)では、アプリは一時的にフォーカスを単一のコンポーネントにロックし、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")
}