虽然设置了autoFocus={true},但键盘未自动弹出

3

我在Modal内部有一个带有autoFocus={true}属性的TextInput。一旦打开ModalTextInput会自动聚焦,但是键盘不会自动弹出。令人惊讶的是,这种情况是随机发生的。有时键盘会弹出,有时不会。这种情况在模拟器和真实设备上都会发生。

有什么建议可以克服这种问题吗?谢谢。


你试过给一个引用并从中调用focus()方法吗? - firats
@firats我们可以从哪里调用.focus方法? - ThinkAndCode
请将以下与编程有关的内容从英语翻译成中文。仅返回翻译后的文本: - firats
5个回答

2
当模态框可见时,您可以使用引用将焦点传递给TextInput。
<Modal onShow={() => {this.textInput.focus()}} > 
    <TextInput ref={input => {this.textInput = input}} />
</Modal>

太棒了!它对我有用。但是我想知道为什么在 onShow 中 TextInput 的 ref 可用,因为此时 TextInput 尚未渲染。 - ThinkAndCode

1

我目前遇到了同样的问题。之前我使用了saumil和其他人提供的解决方案,但是针对函数组件进行了调整:

import React, { useRef } from 'react';
...
let textInput = useRef(null);
<Modal onShow={() => { textInput.focus(); }} ...>
   <TextInput ref={(input) => { textInput = input; }} ... />
</Modal>

它可以工作,但我不太清楚自己在做什么(欢迎解释)。删除autoFocus={true}非常重要,以获得一致的结果。

0

这段代码对我来说是有效的。使用 android:focusedByDefault="true"

    <com.google.android.material.textfield.TextInputLayout
    style="@style/Widget.MaterialComponents.TextInputLayout.OutlinedBox"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:hint="Email">

<com.google.android.material.textfield.TextInputEditText
    android:layout_width="match_parent"
    android:focusedByDefault="true" />

</com.google.android.material.textfield.TextInputLayout>

我认为OP正在寻找更高级别的(React Native)代码。 - ryanwebjackson

0

需要检查一下,

// Keyboard IpM
 InputMethodManager imm = (InputMethodManager)this.getSystemService(Context.INPUT_METHOD_SERVICE);

// input is TextInputEditText in here.
// adding a listener 
input.setOnFocusChangeListener(new View.OnFocusChangeListener() {
    @Override
    public void onFocusChange(View v, boolean isFocused) {

        if (isFocused) {
            imm.toggleSoftInput(InputMethodManager.SHOW_FORCED, 0);
        } 
    }
});

请问我在哪里可以查看这个?您要我将这段代码粘贴到哪里呢,还是它已经存在了? - ThinkAndCode
对于片段(Modal/Dialog),请在onViewCreated()中使用它,为了简单起见,我在这里使用了TextInputEditText。 - hemen
我不了解这些术语,因为我从未听说过。这是在Android Studio中完成的吗?您能告诉我路径吗? - ThinkAndCode

0
你可以尝试使用 focus 方法。像这样;
focus() {
   this.textInputRef.focus();
}


render() {
    return (
      <TextInput
        ref={ref => {
          this.textInputRef = ref;
        }}       
      />
    );
}

现在你可以随时调用focus函数。它将聚焦于文本输入框并立即打开键盘。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接