Android: show soft keyboard automatically when focus is on an EditText
Asked Answered
B

33

377

I'm showing an input box using AlertDialog. The EditText inside the dialog itself is automatically focused when I call AlertDialog.show(), but the soft keyboard is not automatically shown.

How do I make the soft keyboard automatically show when the dialog is shown? (and there is no physical/hardware keyboard). Similar to how when I press the Search button to invoke the global search, the soft keyboard is automatically shown.

Briny answered 8/3, 2010 at 18:19 Comment(5)
This should happen automatically, as per Ted's comment below. Check that first!Devinne
This answer is most simple and works fine: https://mcmap.net/q/74647/-android-show-soft-keyboard-automatically-when-focus-is-on-an-edittextMccallum
Check this link its working for mePhraseology
I've come back to this answer several times over the years. It's always inside a Dialog that I'm having this trouble, never Fragment or Activity.Discretionary
Possible duplicate of Close/hide the Android Soft KeyboardStarknaked
B
320

You can create a focus listener on the EditText on the AlertDialog, then get the AlertDialog's Window. From there you can make the soft keyboard show by calling setSoftInputMode.

final AlertDialog dialog = ...;

editText.setOnFocusChangeListener(new View.OnFocusChangeListener() {
    @Override
    public void onFocusChange(View v, boolean hasFocus) {
        if (hasFocus) {
            dialog.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);
        }
    }
});
Briny answered 10/3, 2010 at 15:54 Comment(13)
How would I do it using the AlertDialog.Builder? ...final AlertDialog.Builder alert = new AlertDialog.Builder(Main.this);Willey
Doesn't work for me - Nexus S. Tried before and after the show().Shainashaine
Doesn't work for me, either. My dialog contains a ListView and I add this listener from its Adapter.Gemmule
@Willey you can get the dialog from the builder by using final AlertDialog dialog = builder.create() and then showon the dialog instead of the builder.Rollick
That works very well - in some cases. For example, if you create a EditText in code and add that to the builder using setView, and then, after builder.create(), use your code above it works fine. However, if I inflate a custom layout (that has a EditText), and add that to the builder using setView, and then try to attach the setOnFocusChangeListener to the EditText in my layout (after retrieving the EditText with findViewById), it won't work.Dominations
I RETRACT MY COMMENT ABOVE I found out that if you can't get the focus right, take a look at your XML! If you see the tag <requestFocus></requestFocus> in there - remove it. It seems like the tag will give focus to the EditText, and then your listener will not be fired as the EditText already has focus.Dominations
I find that if I have a dialog which extends AlertDialog and I try to show the dialog using dialog.show() after constructing the dialog object using the constructor. I am not able to see soft keyboard. However, if I switch to using AlertDialog.Builder() and attach my view to it using Builder.setView() all the EditText's in my dialog automatically show the soft keyboard when needed. I'm very perplexed by this behavior.Unreasoning
Used this to fix a problem with EditText on FragmentDialogGlee
How do you not do this if the device has a hardware keyboard? Seems like this is annoying for those users.Herrah
"MyAlertDialog.getWindow()." doesn't have "setSoftInputMode" function!Steffi
I really don't understand why this is not the default behavior in the SDK. If a view that needs text input shows a blinking cursor, why would someone not want to see the keyboard to input text? It feels so wrong of a UX to meSyne
@ChristianGarcia One of many idiocies built in android. This SDK is incredibly full of bugs.Pesach
@ChristianGarcía Because when Android was released, most devices had a physical keyboard. But yeah the SDK could just check if there's a physical keyboard and act accordingly.Pietra
E
258

For showing keyboard use:

InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.toggleSoftInput(InputMethodManager.SHOW_FORCED,0);

For hiding keyboard use:

InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(view.getWindowToken(),0); 
Epicardium answered 22/6, 2012 at 11:33 Comment(9)
This works particularly well when you want to show/hide the soft keyboard based on toggling the visibility of a view in your layout between VISIBLE and GONE.Midgard
I would suggest using the SHOW_IMPLICIT flag instead, since it means changing activity or application will auto-hide the keyboard as expected.Kabyle
@drspaceboo Using SHOW_IMPLICIT does not work at all for me, I have to use SHOW_FORCED, not sure why...Etalon
When should the above code be run? I tried doing it shortly after adding my layout to its parent. That didn't work. But if I did it after the layout had been around for a while, it did work. So is there a callback that will tell me "If you try to show the keyboard now, it will actually work"?Personate
Or, almost as useful, is there a way to tell whether or not executing the code at a given time will cause the keyboard to be shown? Or, after executing the code, is there a way to tell whether or not it will actually cause the keyboard to appear?Personate
@WilliamJockusch Typically, this should be run on the onFocusChange listener. You would wire this-up by the editText.setOnFocusChangeListerner(...) operation.Nonstandard
toggleSoftInput(InputMethodManager.SHOW_FORCED,0) toggles the soft keyboard. If you want to make sure that the keyboard appears, you can use imm.showSoftInput( view, InputMethodManager.SHOW_IMPLICIT ) instead, where view is the View that will get the input.Pelage
view.getWindowToken() without view: getWindow().getDecorView().getRootView().getWindowToken() Undoubted
Warning! toggleSoftInput(InputMethodManager.SHOW_FORCED solution has a downside: when you press Home button, the keyboard will be shown on home screen. See https://mcmap.net/q/74648/-how-can-i-set-the-focus-and-display-the-keyboard-on-my-edittext-programmatically.Implicative
U
119

You can request a soft keyboard right after creating the dialog (test on SDK - r20)

// create dialog
final AlertDialog dialog = ...; 

// request keyboard   
dialog.getWindow().setSoftInputMode (WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);
Urbanna answered 5/11, 2011 at 6:41 Comment(4)
For anyone wondering, this method does not open the soft keyboard when a hardware keyboard is attached. I just tested with a USB On-The-Go cable. Perfect!Wellintentioned
This doesn't do anything for me.Higherup
I have no hardware keyboard. Maybe configuration(?)Higherup
saved me after hours of struggling ♥Glanville
B
26

I found this example http://android-codes-examples.blogspot.com/2011/11/show-or-hide-soft-keyboard-on-opening.html. Add the following code just before alert.show().

InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.toggleSoftInput(InputMethodManager.SHOW_FORCED,0);
Bradlybradman answered 28/2, 2012 at 6:6 Comment(0)
R
25

I had the same problem and solved it with the following code. I'm not sure how it will behave on a phone with hardware keyboard.

// TextEdit
final EditText textEdit = new EditText(this);

// Builder
AlertDialog.Builder alert = new AlertDialog.Builder(this);
alert.setTitle("Enter text");
alert.setView(textEdit);

alert.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
    @Override
    public void onClick(DialogInterface dialog, int which) {
        String text = textEdit.getText().toString();
        finish();
    }
});

alert.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
    @Override
    public void onClick(DialogInterface dialog, int which) {
        finish();
    }
});

// Dialog
AlertDialog dialog = alert.create();
dialog.setOnShowListener(new OnShowListener() {

    @Override
    public void onShow(DialogInterface dialog) {
        InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.showSoftInput(textEdit, InputMethodManager.SHOW_IMPLICIT);
    }
});

dialog.show();
Rollick answered 11/10, 2011 at 9:51 Comment(3)
It's in the Dialog class API level 8.Rollick
must had been removed later on :/Kalevala
@Xylian it's still in the documentation Dialog.setOnShowListener()Rollick
F
21
<activity
    ...
    android:windowSoftInputMode="stateVisible" >
</activity>

or

getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE);
Faretheewell answered 5/9, 2013 at 22:55 Comment(3)
Thanks a lot mate, this was awesome, actual I used both of them to solve my problem, I had a situation where if user is in add mode, then need to show keyboard on start of activity, and for update mode no keyboard was required by default. So in manifest for activity I set stateHidden and when i detect user is creating new item then i displayed keyboard using code line you have mentioned. :) Once again thanks.Uralite
I get a 'cannot resolve getWindow()' message. i've tried putting 'this.' and other things before it. i want to get the keyboard without using an edittext, just by clicking in a certain part of the screen.Plexiglas
@Androidcoder, it is a part of Activity, so add something like ((Activity) context).getWindow().....Implicative
E
17

Snippets of code from other answers work, but it is not always obvious where to place them in the code, especially if you are using an AlertDialog.Builder and followed the official dialog tutorial because it doesn't use final AlertDialog ... or alertDialog.show().

alertDialog.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);

Is preferable to

InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.toggleSoftInput(InputMethodManager.SHOW_FORCED,0);

Because SOFT_INPUT_STATE_ALWAYS_VISIBLE will hide the keyboard if the focus switches away from the EditText, where SHOW_FORCED will keep the keyboard displayed until it is explicitly dismissed, even if the user returns to the homescreen or displays the recent apps.

Below is working code for an AlertDialog created using a custom layout with an EditText defined in XML. It also sets the keyboard to have a "go" key and allows it to trigger the positive button.

alert_dialog.xml:

<RelativeLayout
android:id="@+id/dialogRelativeLayout"
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content" >

    <!-- android:imeOptions="actionGo" sets the keyboard to have a "go" key instead of a "new line" key. -->
    <!-- android:inputType="textUri" disables spell check in the EditText and changes the "go" key from a check mark to an arrow. -->
    <EditText
        android:id="@+id/editText"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="16dp"
        android:layout_marginLeft="4dp"
        android:layout_marginRight="4dp"
        android:layout_marginBottom="16dp"
        android:imeOptions="actionGo"
        android:inputType="textUri"/>

</RelativeLayout>

AlertDialog.java:

import android.app.Activity;
import android.app.Dialog;
import android.content.DialogInterface;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.DialogFragment;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatDialogFragment;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.widget.EditText;

public class CreateDialog extends AppCompatDialogFragment {
    // The public interface is used to send information back to the activity that called CreateDialog.
    public interface CreateDialogListener {
        void onCreateDialogCancel(DialogFragment dialog);    
        void onCreateDialogOK(DialogFragment dialog);
    }

    CreateDialogListener mListener;

    // Check to make sure that the activity that called CreateDialog implements both listeners.
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        try {
            mListener = (CreateDialogListener) activity;
        } catch (ClassCastException e) {
            throw new ClassCastException(activity.toString() + " must implement CreateDialogListener.");
        }
    }

    // onCreateDialog requires @NonNull.
    @Override
    @NonNull
    public Dialog onCreateDialog(Bundle savedInstanceState) {
        AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(getActivity());
        LayoutInflater customDialogInflater = getActivity().getLayoutInflater();

        // Setup dialogBuilder.
        alertDialogBuilder.setTitle(R.string.title);
        alertDialogBuilder.setView(customDialogInflater.inflate(R.layout.alert_dialog, null));
        alertDialogBuilder.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                mListener.onCreateDialogCancel(CreateDialog.this);
            }
        });
        alertDialogBuilder.setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                mListener.onCreateDialogOK(CreateDialog.this);
            }
        });

        // Assign the resulting built dialog to an AlertDialog.
        final AlertDialog alertDialog = alertDialogBuilder.create();

        // Show the keyboard when the dialog is displayed on the screen.
        alertDialog.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);

        // We need to show alertDialog before we can setOnKeyListener below.
        alertDialog.show();

        EditText editText = (EditText) alertDialog.findViewById(R.id.editText);

        // Allow the "enter" key on the keyboard to execute "OK".
        editText.setOnKeyListener(new View.OnKeyListener() {
            public boolean onKey(View v, int keyCode, KeyEvent event) {
                // If the event is a key-down event on the "enter" button, select the PositiveButton "OK".
                if ((event.getAction() == KeyEvent.ACTION_DOWN) && (keyCode == KeyEvent.KEYCODE_ENTER)) {
                    // Trigger the create listener.
                    mListener.onCreateDialogOK(CreateDialog.this);

                    // Manually dismiss alertDialog.
                    alertDialog.dismiss();

                    // Consume the event.
                    return true;
                } else {
                    // If any other key was pressed, do not consume the event.
                    return false;
                }
            }
        });

        // onCreateDialog requires the return of an AlertDialog.
        return alertDialog;
    }
}
Electronics answered 17/12, 2015 at 5:7 Comment(0)
P
16

I know this question is old by I think using an extension function is a prettier way to show keyboard for an edit text

here is the method I use to show keyboard for an edittext.

kotlin code: just need to call edittext.showKeyboard()

fun EditText.showKeyboard() {
  post {
    requestFocus()
    val imm = context.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
    imm.showSoftInput(this, InputMethodManager.SHOW_IMPLICIT)
  }
}

the java code:

public static void showKeyboard(EditText editText) {
    editText.post(new Runnable() {
      @Override
      public void run() {
        editText.requestFocus();
        InputMethodManager imm = (InputMethodManager) editText.getContext()
            .getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.showSoftInput(editText, InputMethodManager.SHOW_IMPLICIT);
      }
    });
  }
Pecoraro answered 6/7, 2019 at 4:52 Comment(0)
C
11

Well, this is a pretty old post, still there is something to add.
These are 2 simple methods that help me to keep keyboard under control and they work just perfect:

Show keyboard

public void showKeyboard() {
    InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
    View v = getCurrentFocus();
    if (v != null)
        imm.showSoftInput(v, 0);
}

Hide keyboard

public void hideKeyboard() {
    InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
    View v = getCurrentFocus();
    if (v != null)
        imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
}
Chequerboard answered 11/10, 2015 at 20:49 Comment(2)
What is getCurrentFocus()?Implicative
I see, that's a method of an Activity.Implicative
P
10

Let me point some additional info to the solution of yuku, because I found it hard to get this working! How do I get the AlertDialog object from my AlertDialog.Builder? Well, it's the result of my alert.show() execution:

final AlertDialog.Builder alert = new AlertDialog.Builder(getActivity());
final EditText input = new EditText(getActivity());
alert.setView(input);

// do what you need, like setting positive and negative buttons...

final AlertDialog dialog = alert.show();

input.setOnFocusChangeListener(new OnFocusChangeListener() {
   @Override
   public void onFocusChange(View v, boolean hasFocus) {
      if(hasFocus) {
         dialog.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);
      }
   }
});
Parish answered 20/12, 2012 at 15:5 Comment(0)
T
7

Take a look at this discussion which handles manually hiding and showing the IME. However, my feeling is that if a focused EditText is not bringing the IME up it is because you are calling AlertDialog.show() in your OnCreate() or some other method which is evoked before the screen is actually presented. Moving it to OnPostResume() should fix it in that case I believe.

Tush answered 8/3, 2010 at 19:13 Comment(0)
W
6

Yes you can do with setOnFocusChangeListener it will help you.

editText.setOnFocusChangeListener(new View.OnFocusChangeListener() {
    @Override
    public void onFocusChange(View v, boolean hasFocus) {
        if (hasFocus) {
            dialog.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);
        }
    }
});
Wipe answered 21/6, 2012 at 8:50 Comment(0)
L
4

If anyone is getting:

Cannot make a static reference to the non-static method getSystemService(String) from the type Activity

Try adding context to getSystemService call.

So

InputMethodManager imm = 
(InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
imm.toggleSoftInput(InputMethodManager.SHOW_FORCED,0);
Livable answered 9/6, 2012 at 19:59 Comment(0)
C
4

My method uses the new way for Android 11+ and also supports older versions:

fun Fragment.showKeyboard() {
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
        ViewCompat.getWindowInsetsController(requireView())?.show(WindowInsetsCompat.Type.ime())
    } else {
        val focusedView = view?.findFocus() ?: view?.apply { requestFocus() }
        val imm = (context?.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager)
        val isShowSucceeded = imm.showSoftInput(focusedView, InputMethodManager.SHOW_IMPLICIT)
        if(!isShowSucceeded) {
            imm.toggleSoftInputFromWindow(
                view?.windowToken, 0, InputMethodManager.HIDE_IMPLICIT_ONLY)
    }
}

}

Cytochrome answered 23/1, 2022 at 13:8 Comment(1)
Thank you! ViewCompat.getWindowInsetsController(binding.root)?.show(WindowInsetsCompat.Type.ime()) works perfectly!Gadroon
R
2

The problem seems to be that since the place where you enter text is hidden initially (or nested or something), AlertDialog is automatically setting the flag WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM or WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE so that things don't trigger a soft input to show up.

The way that to fix this is to add the following:

(...)
// Create the dialog and show it
Dialog dialog = builder.create()
dialog.show();

// After show (this is important specially if you have a list, a pager or other view that uses a adapter), clear the flags and set the soft input mode
dialog.getWindow().clearFlags(WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE|WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM);
dialog.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);
Rateable answered 2/12, 2014 at 5:4 Comment(1)
This should have more upvotes.Cowie
E
2

We can open keyboard by default when dialogue display using

dialog.getWindow().clearFlags(WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE | WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM)
dialog.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE)
Everyday answered 17/10, 2022 at 5:3 Comment(0)
D
1

The original question concerns Dialogs and my EditText is on a regular view. Anyhow, I suspect this should work for most of you too. So here's what works for me (the above suggested highest rated method did nothing for me). Here's a custom EditView that does this (subclassing is not necessary, but I found it convenient for my purposes as I wanted to also grab the focus when the view becomes visible).

This is actually largely the same as the tidbecks answer. I actually didn't notice his answer at all as it had zero up votes. Then I was about to just comment his post, but it would have been too long, so I ended doing this post anyways. tidbeck points out that he's unsure how it works with devices having keyboards. I can confirm that the behaviour seems to be exactly the same in either case. That being such that on portrait mode the software keyboard gets popped up and on landscape it doesn't. Having the physical keyboard slid out or not makes no difference on my phone.

Because, I personally found the behaviour a bit awkward I opted for using: InputMethodManager.SHOW_FORCED. This works as I wanted it to work. The keyboard becomes visible regardless of the orientation, however, at least on my device it doesn't pop up if the hardware keyboard has been slid out.

import android.app.Service;
import android.content.Context;
import android.util.AttributeSet;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;

public class BringOutTheSoftInputOnFocusEditTextView extends EditText {

    protected InputMethodManager inputMethodManager;

    public BringOutTheSoftInputOnFocusEditTextView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        init();
    }

    public BringOutTheSoftInputOnFocusEditTextView(Context context, AttributeSet attrs) {
        super(context, attrs);
        init();
    }

    public BringOutTheSoftInputOnFocusEditTextView(Context context) {
        super(context);
        init();
    }

    private void init() {
        this.inputMethodManager = (InputMethodManager)getContext().getSystemService(Service.INPUT_METHOD_SERVICE);
        this.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if (hasFocus) {
                    BringOutTheSoftInputOnFocusEditTextView.this.inputMethodManager.showSoftInput(BringOutTheSoftInputOnFocusEditTextView.this, InputMethodManager.SHOW_FORCED);
                }
            }
        });
    }

    @Override
    protected void onVisibilityChanged(View changedView, int visibility) {
        super.onVisibilityChanged(changedView, visibility);
        if (visibility == View.VISIBLE) {
            BringOutTheSoftInputOnFocusEditTextView.this.requestFocus();
        }
    }

}
Disillusionize answered 25/10, 2011 at 18:26 Comment(0)
A
1

try and use:

editText.requestFocus();
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.toggleSoftInput(InputMethodManager.SHOW_FORCED, InputMethodManager.HIDE_IMPLICIT_ONLY);
Anthurium answered 19/2, 2015 at 0:43 Comment(0)
H
1

To show keyboard, for me, I had to do the following

Android TextField : set focus + soft input programmatically

Essentially the solution is the following

@Override
public void onResume() {
    super.onResume();
    //passwordInput.requestFocus(); <-- that doesn't work
    passwordInput.postDelayed(new ShowKeyboard(), 325); //250 sometimes doesn't run if returning from LockScreen
}

Where ShowKeyboard is

private class ShowKeyboard implements Runnable {
    @Override
    public void run() {
        passwordInput.setFocusableInTouchMode(true);
        //passwordInput.requestFocusFromTouch(); //this gives touch event to launcher in background -_-
        passwordInput.requestFocus();
        getActivity().getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);
        ((InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE)).showSoftInput(passwordInput, 0);
    }
}

After a successful input, I also make sure I hide the keyboard

getActivity().getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);
((InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE))
                    .hideSoftInputFromWindow(getView().getWindowToken(), 0);
Heave answered 24/3, 2015 at 10:41 Comment(0)
B
1
getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);

I call this in onCreate() to show keyboard automatically, when I came in the Activity.

Barahona answered 12/9, 2018 at 2:31 Comment(1)
My nightmare is finally over!Zoochemistry
L
1

Put these methods in your Util class and use anywhere.

Kotlin

fun hideKeyboard(activity: Activity) {
    val view = activity.currentFocus
    val methodManager = activity.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
    assert(view != null)
    methodManager.hideSoftInputFromWindow(view!!.windowToken, InputMethodManager.HIDE_NOT_ALWAYS)
}

private fun showKeyboard(activity: Activity) {
    val view = activity.currentFocus
    val methodManager = activity.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
    assert(view != null)
    methodManager.showSoftInput(view, InputMethodManager.SHOW_IMPLICIT)
}

Java

public static void hideKeyboard(Activity activity) {
    View view = activity.getCurrentFocus();
    InputMethodManager methodManager = (InputMethodManager) activity.getSystemService(Context.INPUT_METHOD_SERVICE);
    assert methodManager != null && view != null;
    methodManager.hideSoftInputFromWindow(view.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
}

private static void showKeyboard(Activity activity) {
    View view = activity.getCurrentFocus();
    InputMethodManager methodManager = (InputMethodManager) activity.getSystemService(Context.INPUT_METHOD_SERVICE);
    assert methodManager != null && view != null;
    methodManager.showSoftInput(view, InputMethodManager.SHOW_IMPLICIT);
}
Luu answered 1/10, 2018 at 10:2 Comment(0)
S
1

I created nice kotlin-esqe extension functions incase anyone is interested

fun Activity.hideKeyBoard() {
    val view = this.currentFocus
    val methodManager = this.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
    assert(view != null)
    methodManager.hideSoftInputFromWindow(view!!.windowToken, InputMethodManager.HIDE_NOT_ALWAYS)
}

fun Activity.showKeyboard() {
    val view = this.currentFocus
    val methodManager = this.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
    assert(view != null)
    methodManager.showSoftInput(view, InputMethodManager.SHOW_IMPLICIT)
}
Stalky answered 7/10, 2018 at 21:29 Comment(0)
P
1

Tried many but this is what worked for me (kotlin):

        val dialog = builder.create()
        dialog.setOnShowListener {
            nameEditText.requestFocus()
            val s = ContextCompat.getSystemService(requireContext(), InputMethodManager::class.java)
            s?.toggleSoftInput(InputMethodManager.SHOW_FORCED, 0)
        }

        dialog.setOnDismissListener {
            val s = ContextCompat.getSystemService(requireContext(), InputMethodManager::class.java)
            s?.toggleSoftInput(InputMethodManager.HIDE_IMPLICIT_ONLY, 0)
        }

        dialog.show()
Parnas answered 29/5, 2019 at 8:42 Comment(0)
A
1

just add this line to manifest file necessary activity.

android:windowSoftInputMode="stateVisible"

Apomixis answered 1/10, 2020 at 5:8 Comment(1)
After I upvoted this answer and it was too late to change my vote, I found out that it didn't work for me in all cases.Zoochemistry
N
0

This is good sample for you :

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <ScrollView
        android:id="@+id/scrollID"
        android:layout_width="fill_parent"
        android:layout_height="0dip"
        android:layout_weight="1" >

        <LinearLayout
            android:id="@+id/test"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="vertical" >
        </LinearLayout>
    </ScrollView>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:baselineAligned="true"
        android:orientation="horizontal"
        android:paddingBottom="5dp"
        android:paddingLeft="5dp"
        android:paddingRight="5dp"
        android:weightSum="1" >

        <EditText
            android:id="@+id/txtInpuConversation"
            android:layout_width="0dip"
            android:layout_height="wrap_content"
            android:layout_weight="0.5"
            android:hint="@string/edt_Conversation" >

            <requestFocus />
        </EditText>

        <Button
            android:id="@+id/btnSend"
            android:layout_width="0dip"
            android:layout_height="wrap_content"
            android:layout_weight="0.5"
            android:text="@string/btn_Conversation" />
    </LinearLayout>

</LinearLayout>
Nehemiah answered 20/8, 2014 at 10:53 Comment(0)
G
0

Why this answer - Because above solution will show your keyboard but it will not vanish if you click anywhere other that EditText. So you need to do something to make the keybaord disappear when EditText loses focus.

You can achieve this by doing the following steps:

  1. Make the parent view(content view of your activity) clickable and focusable by adding the following attributes

        android:clickable="true" 
        android:focusableInTouchMode="true" 
    
  2. Implement a hideKeyboard() method

        public void hideKeyboard(View view) {
            InputMethodManager inputMethodManager =(InputMethodManager)getSystemService(Activity.INPUT_METHOD_SERVICE);
            inputMethodManager.hideSoftInputFromWindow(view.getWindowToken(),InputMethodManager.HIDE_IMPLICIT_ONLY );
        }
    
  3. Lastly, set the onFocusChangeListener of your edittext.

        edittext.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if (!hasFocus) {
                    hideKeyboard(v);
                }
            }
        });
    
Gang answered 10/9, 2014 at 11:59 Comment(0)
T
0

This is bit tricky. I did in this way and it worked.

1.At first call to hide the soft Input from the window. This will hide the soft input if the soft keyboard is visible or do nothing if it is not.

2.Show your dialog

3.Then simply call to toggle soft input.

code:

InputMethodManager inputManager = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE); 
//hiding soft input
inputManager.hideSoftInputFromWindow(findViewById(android.R.id.content).getWind‌​owToken(), 0);
//show dialog
yourDialog.show();
//toggle soft input
inputManager.toggleSoftInput(InputMethodManager.SHOW_FORCED,InputMethodManager.SHOW_IMPLICIT);
Trigger answered 26/2, 2015 at 17:46 Comment(0)
C
0

Try this

SomeUtils.java

public static void showKeyboard(Activity activity, boolean show) {
    InputMethodManager inputMethodManager = (InputMethodManager) activity.getSystemService(Context.INPUT_METHOD_SERVICE);

    if(show)
        inputMethodManager.toggleSoftInput(InputMethodManager.SHOW_FORCED,0);
    else
        inputMethodManager.toggleSoftInput(InputMethodManager.HIDE_IMPLICIT_ONLY,0);
}
Chessa answered 29/8, 2018 at 23:54 Comment(0)
I
0

Looking at https://mcmap.net/q/74648/-how-can-i-set-the-focus-and-display-the-keyboard-on-my-edittext-programmatically I simplified a bit:

// In onCreateView():
view.edit_text.run {
    requestFocus()
    post { showKeyboard(this) }
}

fun showKeyboard(view: View) {
    val imm = view.context.getSystemService(
        Context.INPUT_METHOD_SERVICE) as InputMethodManager?
    imm?.showSoftInput(view, InputMethodManager.SHOW_IMPLICIT)
}

It is better than https://mcmap.net/q/74647/-android-show-soft-keyboard-automatically-when-focus-is-on-an-edittext:

InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.toggleSoftInput(InputMethodManager.SHOW_FORCED, 0);

because when you press Home button and move to home screen, the keyboard will stay open.

Implicative answered 5/10, 2018 at 10:39 Comment(0)
E
0

This problem with displaying soft keyboard from EditText inside AlertDialog is probably in the AlertDialog.show(), because the EditText was applied after displaying AlertDialog. I'm not sure that's the case in all versions of the API, but I think the solution comes with API level 21, because it comes with AlertDialog.create(), which should be called before AlertDialog.show().

Here is my best solution for this case. First, create somewhere:

    private int showKeyboard(View view) {
        final InputMethodManager inputManager = (InputMethodManager) requireActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
        if (inputManager != null) {
            boolean isShown = inputManager.showSoftInput(view, InputMethodManager.SHOW_IMPLICIT); // flag=InputMethodManager.SHOW_IMPLICIT ili =
            return (isShown) ? 1: -1;
        }
        return 0;
    }

Then, after your AlertDialog.Builder builder = new AlertDialog.Builder(requireContext()); continue with:

    EditText editText = new EditText(requireContext());
    builder.setView(editText);
    // ... put positive-negative buttons, and etc ...
    AlertDialog dialog = builder.create(); // Create dialog from builder
    dialog.setCancelable(false); // If you need
    Handler handler = new Handler();
    dialog.setOnShowListener(new DialogInterface.OnShowListener() {
        @Override
        public void onShow(DialogInterface dialog) { // 1. When a dialog is displayed
            editText.requestFocus();
            Runnable runnable = new Runnable() { // create one runnable
                int counter = 0;
                public void run() {
                    int status = showKeyboard(editText); // 2. Call func.above for keyboard, but...
                    if(status == -1 && counter < 10){ handler.postDelayed(this, 100); counter ++; } // ...if it inst shown call again after 100ms
                }
            };
            runnable.run(); // Execute runnable first time here
        }
    });
    dialog.show();

Dont forget import android.os.Handler; and etc. ;-)

Thanks for Vote Up.

Eogene answered 25/4, 2021 at 19:36 Comment(0)
D
0

This works for me. I set an OnShowListener for the dialog, in that listener, I set an onFocusChangeListener for the textfield and in that FocusChangeListener I call showSoftInput with a 100ms delay and then remove the FocusChangeListener, so it only handles the first focus change.

When calling dialog.show(), the OnShowListener is invoked, which requests focus for the textfield. When the textfield gets the focus, the FocusChangeListener is called and eventually shows the keyboard.

    val views = DialogBinding.inflate(layoutInflater) // layout with 'textfield'
    val dialog = MaterialAlertDialogBuilder(requireContext())
        .setTitle("Exercise")
        .setView(views.root)
        ...
        .create()
    dialog.setOnShowListener {
        views.textfield.onFocusChangeListener = View.OnFocusChangeListener { view, _ ->
            view.postDelayed({
                (view.context.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager).showSoftInput(view, 0)
            }, 100)                
            views.textfield.onFocusChangeListener = null
        }
        views.repcount.requestFocus()
    }
    dialog.show()
Different answered 30/9, 2022 at 19:14 Comment(0)
M
0

You could attach an onFocusListener on the EditText or an onShowListener on the AlertDialog and add the following:

val methodManager = activity.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
methodManager.showSoftInput(view, InputMethodManager.SHOW_IMPLICIT)
Madelyn answered 5/11, 2022 at 15:33 Comment(0)
M
0

edittext.setShowSoftInputOnFocus(true); is the smoothest solution on the topic of thhe question.

AlertDialog.Builder alertSearch = new AlertDialog.Builder(activity);
alertSearch.setIcon(R.drawable.ic_launcher);
alertSearch.setTitle("Search");
final EditText edittext = new EditText(activity);
edittext.setSingleLine();
edittext.setHint("...");
edittext.setText(SearchString);

Set keyboard when on Focus

edittext.setShowSoftInputOnFocus(true);

Get Focus

edittext.requestFocus();

And

alertSearch.setView(edittext);
alertSearch.setPositiveButton("OK", new DialogInterface.OnClickListener() {
    public void onClick(DialogInterface dialog, int whichButton) {
        // Do something
        act.recreate();
    }
});
alertSearch.show();
Mayor answered 16/11, 2022 at 20:57 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.