ThinkAndCode
ThinkAndCode

Reputation: 1667

Keyboard is not opening automatically though autoFocus={true}

I have a TextInput inside a Modal with autoFocus={true}. As soon as Modal is opened TextInput is focused automatically but keyboard is not opening automatically.And surprisingly this is happening randomly. sometimes keyboard opens and sometimes not. This is happening in both emulator and real device.

Any suggestions to overcome this behavior? Thank You.

Upvotes: 4

Views: 2837

Answers (5)

Satish Singh
Satish Singh

Reputation: 81

This code is working for me. Use 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>

Upvotes: 0

Mollifier
Mollifier

Reputation: 37

I'm having the same problem currently. I used the solution suggestes by saumil and others previously; but adjusted for functional components:

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

It works, but I don't quite know what I'm doing (explanations welcomed). It's important to delete the autoFocus={true} to get consistent results.

Upvotes: 1

user11766764
user11766764

Reputation:

you can pass focus to TextInput using reference whenever a Modal is visible

<Modal onShow={() => {this.textInput.focus()}} > 
    <TextInput ref={input => {this.textInput = input}} />
</Modal>

Upvotes: 4

firats
firats

Reputation: 526

You can try focus method. Like this;

focus() {
   this.textInputRef.focus();
}


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

Now you can call focus function whenever you want. It will focus on the textinput and open the keyboard immediately.

Upvotes: 0

hemen
hemen

Reputation: 1490

Need to check though,

// 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);
        } 
    }
});

Upvotes: 0

Related Questions