简体   繁体   English

当我专注于 Jetpack Compose 中的 BasicTextField 时,如何禁用软键盘

[英]How can I disable softKeyboard when I focus on the BasicTextField in Jetpack Compose

I have a BasicTextField and I want it to focus by default when the screen opens and the keyboard to be close in all cases and not open.我有一个 BasicTextField,我希望它在屏幕打开并且键盘在所有情况下都关闭而不打开时默认聚焦。

How can I do that?我怎样才能做到这一点?

One way is... You can specify android:windowSoftInputMode="stateAlwaysHidden in manifest for that activity一种方法是......您可以在该活动的清单中指定android:windowSoftInputMode="stateAlwaysHidden

Pros:优点:

  • It does the job to some extent without much code它在某种程度上不需要太多code就可以完成这项工作

Cons:缺点:

  • If the user presses on the edit text rapidly you can see the keyboard for some frames.如果用户快速按下编辑文本,您可以看到某些帧的键盘。 Which may make users go crazy这可能会让用户 go 抓狂
  • If you have other edit text which is editable in the same activity then you need to manually check for focus events and set this programmatically如果您有其他可在同一活动中编辑的编辑文本,则需要手动检查焦点事件并以编程方式设置

Tip: If you are planning to allow users to only paste how about reading the data from the clipboard service and display it by default and make some UI changes to give options to users to go with that value or not...提示:如果您打算只允许用户粘贴如何从剪贴板服务读取数据并默认显示它,并进行一些 UI 更改以向用户提供 go 的选项是否具有该值...

class MainActivity : ComponentActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContent {
            Ui()
        }
    }
}

@Composable
fun Ui() {
    MyApplicationTheme {
        // A surface container using the 'background' color from the theme
        Surface(color = MaterialTheme.colors.background) {
            Greeting()
        }
    }
}

@Composable
fun Greeting() {
    var value by remember {
        mutableStateOf("")
    }
    val focusManager = LocalFocusManager.current
    TextField(
        value = value,
        onValueChange = { value = it },
        keyboardOptions = KeyboardOptions(imeAction = ImeAction.Done),
        keyboardActions = KeyboardActions(onDone = { focusManager.clearFocus() })
    )
}

@Preview(showBackground = true)
@Composable
fun DefaultPreview() {
    Ui()
}

Just as in above code get current focus and clear it.就像上面的代码一样,获取当前焦点并清除它。 or you can also hide keyboard using LocalSoftwareKeyboardController just like focusManager.或者您也可以像 focusManager 一样使用LocalSoftwareKeyboardController隐藏键盘。

val localSoftwareKeyboardController = LocalSoftwareKeyboardController.current

.... ……

keyboardActions = KeyboardActions(onDone = { localSoftwareKeyboardController?.hide() })

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM