Jetpack Compose 中没有焦点的 OnKeyEvent

OnKeyEvent without focus in Jetpack Compose

我正在创建一个使用设备上的物理按钮的应用程序。

此按钮将具有不同的功能,具体取决于处于活动状态的屏幕。

对于活动,我要做的是为每个屏幕设置一个 Activity,并且在每个屏幕中我将覆盖 onKeyDown 函数。我如何使用在不同 Jetpack Compose 屏幕之间导航的单个 activity 来执行此操作? 根据 Android 文档,正确的方法应该是这样的...

Box(modifier = Modifier
    .onKeyEvent {
        Log.e("Pressed", it.nativeKeyEvent.keyCode.toString())
        true
    }
    .focusable()
    .fillMaxSize()
    .background(Color.Gray)
) {
    // All screen components
}

但这只有在屏幕上的某个元素被聚焦时才有效,我需要的是它是否始终有效,有没有办法实现这一点?

一种选择是将焦点保持在视图上,以便 Modifier.onKeyEvent 始终有效。请注意,它可能与其他可聚焦视图冲突,例如 TextField,因此所有这些视图都应该是此 always-focusable 视图的子视图(在任何级别)。

val focusRequester = remember { FocusRequester() }
var hasFocus by remember { mutableStateOf(false) }
Box(
    Modifier
        .focusRequester(focusRequester)
        .onFocusChanged {
            hasFocus = it.hasFocus
        }
        .focusable()
        .onKeyEvent {
            TODO()
        }
) {
}
if (!hasFocus) {
    LaunchedEffect(Unit) {
        focusRequester.requestFocus()
    }
}

另一种选择是创建组合本地处理程序并从您的 activity:

传递事件
class MainActivity : AppCompatActivity() {
    private val keyEventHandlers = mutableListOf<KeyEventHandler>()

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        setContent {
            CompositionLocalProvider(LocalKeyEventHandlers provides keyEventHandlers) {
                // your app
            }
        }
    }

    override fun onKeyDown(keyCode: Int, event: KeyEvent): Boolean {
        return keyEventHandlers.reversed().any { it(keyCode, event) } || super.onKeyDown(keyCode, event)
    }
}

val LocalKeyEventHandlers = compositionLocalOf<MutableList<KeyEventHandler>> {
    error("LocalKeyEventHandlers is not provided")
}

typealias KeyEventHandler = (Int, KeyEvent) -> Boolean

@Composable
fun ListenKeyEvents(handler: KeyEventHandler) {
    val handlerState = rememberUpdatedState(handler)
    val eventHandlers = LocalKeyEventHandlers.current
    DisposableEffect(handlerState) {
        val localHandler: KeyEventHandler = {
            handlerState.value(it)
        }
        eventHandlers.add(localHandler)
        onDispose {
            eventHandlers.remove(localHandler)
        }
    }
}

用法:

ListenKeyEvents { code, event ->
    TODO()
}