如何在Compose中获取初始焦点。

huangapple go评论52阅读模式
英文:

How to get initial focus in compose

问题

如何在Android Compose应用程序上获取初始键盘焦点?

我的视图如下:

父组件 { 子组件 { 按钮 } }

我尝试在父组件的函数中实现它...

FocusRequester未初始化。以下是一些可能的修复方法:

1. 记住FocusRequester:val focusRequester = remember { FocusRequester() }

2. 是否忘记添加Modifier.focusRequester()?

3. 您是否尝试在组合期间请求焦点?应该在响应某些事件时发出焦点请求。例如Modifier.clickable { focusRequester.requestFocus() }
英文:

How to get initial keyboard focus on an Android compose app?

My view looks like

Parent { Child { Button} }

I tried implementing it in the Parent composable function....

FocusRequester is not initialized. Here are some possible fixes:
                                                                                                
                                                                                                   
1. Remember the FocusRequester: val focusRequester = remember { FocusRequester() }
                                                                                                   
2. Did you forget to add a Modifier.focusRequester() ?
                                                                                                   
3. Are you attempting to request focus during composition? Focus requests should be made in response to some event. Eg Modifier.clickable { focusRequester.requestFocus() }

答案1

得分: 1

以下是翻译好的部分:

原文:
This error does not happen when implementing it in the composable function, where the target element is a direct child....

翻译:
当在可组合函数中实现它,其中目标元素是直接子元素时,不会发生此错误....

原文:
So implementing it in the Child seems to be a solution....

翻译:
因此,在 Child 中实现似乎是一个解决方案....

英文:

The following code woirks like a charm....

fun Modifier.requestInitialFocus() = composed {
    val first = remember { FocusRequester() }
    LaunchedEffect(first) {
        delay(1)
        first.requestFocus()
    }
    focusRequester(first)
}

Original:

This error does not happen when implementing it in the composable function, where the target element is a direct child....

So implementing it in the Child seems to be a solution....

huangapple
  • 本文由 发表于 2023年2月8日 19:35:30
  • 转载请务必保留本文链接:https://go.coder-hub.com/75385213.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定