Hide keyboard in AlertDialog - android

I have an alertdialog with an editext. For this Edittext I make keyboard appear and I want that when user press ok or cancel to hide the keyboard. The strange problem is that when user choose ok, the keyboard is hide, but when choose cancel the keyboard doesn't hide an I'm using the same code for both cases.
Here is my code :
final AlertDialog.Builder alert = new AlertDialog.Builder(this);
alert.setTitle(data);
final EditText input = new EditText(this);
InputFilter[] FilterArray = new InputFilter[1];
FilterArray[0] = new InputFilter.LengthFilter(25);
input.setFilters(FilterArray);
input.postDelayed(new Runnable() {
#Override
public void run() {
InputMethodManager keyboard = (InputMethodManager)
getSystemService(Context.INPUT_METHOD_SERVICE);
keyboard.showSoftInput(input, 0);
}
},200);
alert.setView(input);
alert.setPositiveButton(ok, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
text = input.getText().toString().trim();
Canvas c = new Canvas(bitmapResult);
drawTextImage(bitmapResult);
saveimage();
InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(input.getWindowToken(), 0);
}
});
alert.setNegativeButton(cancel,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
dialog.cancel();
saveimage();
InputMethodManager im = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
im.hideSoftInputFromWindow(input.getWindowToken(), 0);
}
});
alert.show();
where is my mystake? Can anyone help me?

I found the solution :
alert.setNegativeButton(cancel,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
saveimage();
InputMethodManager im = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
im.hideSoftInputFromWindow(input.getWindowToken(), 0);
dialog.cancel();
}
});
I should've put dialog.cancel() after I hide the keyboard.
UPDATE IN KOTLIN:
val im: InputMethodManager =
getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
im.hideSoftInputFromWindow(editText.windowToken, 0)

I too was struggling with this and bonked my head on just about every "solution" which was posted yet the damn keyboard would still not close. Then I had a caffenated vision:
InputMethodManager imm = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(dialog.getWindow().getDecorView().getWindowToken(), InputMethodManager.HIDE_IMPLICIT_ONLY);
}
Note the HIDE_IMPLICIT_ONLY
hope that helps anyone else struggling with this problem.

In my case i wanted keyboard to be open only when the dialog shown
i have tried many solutions but finally i have succeeded to achieve by adding
android:windowSoftInputMode="stateAlwaysHidden"
inside tag of manifiest file.

Not sure, but you can try with adding this:
getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
I'm using it to avoid the first display of the keyboard when my app starts... when I click in the field, the keyboard is still opened...
So, maybe, it could work with your code:
keyboard.showSoftInput(input, 0);
and then automatically close it...

Use following method before you use dialog.cancel();
public static void hideSoftKeyboardUsingView(Context context,View view) {
InputMethodManager imm = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(view.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
}

Tried all of the above but finally this works for me... after a few lost hair -_-
mDialogView.btn.setOnClickListener {
mAlertDialog.dismiss()
val imm = this#MainActivity.getSystemService(Context.INPUT_METHOD_SERVICE) as
InputMethodManager
imm.toggleSoftInput(InputMethodManager.HIDE_IMPLICIT_ONLY, 0)
}

Related

Hide soft keyboard works for one EditText but does not work properly for the other [duplicate]

I want to automatically show the soft-keyboard when an EditText is focused (if the device does not have a physical keyboard) and I have two problems:
When my Activity is displayed, my EditText is focused but the keyboard is not displayed, I need to click again on it to show the keyboard (it should be displayed when my Activity is displayed).
And when I click done on the keyboard, the keyboard is dissmissed but the EditText stays focused and y don't want (because my edit is done).
To resume, my problem is to have something more like on the iPhone: which keep the keyboard sync with my EditText state (focused / not focused) and of course does not present a soft-keyboard if there is a physical one.
To force the soft keyboard to appear, you can use
EditText yourEditText= (EditText) findViewById(R.id.yourEditText);
yourEditText.requestFocus();
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.showSoftInput(yourEditText, InputMethodManager.SHOW_IMPLICIT);
And for removing the focus on EditText, sadly you need to have a dummy View to grab focus.
To close it you can use
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(yourEditText.getWindowToken(), 0);
This works for using it in a dialog
public void showKeyboard(){
InputMethodManager inputMethodManager = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
inputMethodManager.toggleSoftInput(InputMethodManager.SHOW_FORCED, 0);
}
public void closeKeyboard(){
InputMethodManager inputMethodManager = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
inputMethodManager.toggleSoftInput(InputMethodManager.HIDE_IMPLICIT_ONLY, 0);
}
I had the same problem. Immediately after editText VISIBILITY change from GONE to VISIBLE, I had to set the focus and display the soft keyboard. I achieved this using the following code:
new Handler().postDelayed(new Runnable() {
public void run() {
// ((EditText) findViewById(R.id.et_find)).requestFocus();
//
EditText yourEditText= (EditText) findViewById(R.id.et_find);
// InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
// imm.showSoftInput(yourEditText, InputMethodManager.SHOW_IMPLICIT);
yourEditText.dispatchTouchEvent(MotionEvent.obtain(SystemClock.uptimeMillis(), SystemClock.uptimeMillis(), MotionEvent.ACTION_DOWN, 0f, 0f, 0));
yourEditText.dispatchTouchEvent(MotionEvent.obtain(SystemClock.uptimeMillis(), SystemClock.uptimeMillis(), MotionEvent.ACTION_UP, 0f, 0f, 0));
}
}, 200);
It works for me with 100ms delay, but failed without any delay or with only a delay of 1ms.
Commented part of code shows another approach, which works only on some devices. I tested on OS versions 2.2 (emulator), 2.2.1 (real device) and 1.6 (emulator).
This approach saved me a lot of pain.
To cause the keyboard to appear, use
getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE);
This method is more reliable than invoking the InputMethodManager directly.
To close it, use
getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);
When nothing else works, force it to be shown:
editText.requestFocus();
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.toggleSoftInput(InputMethodManager.SHOW_FORCED, InputMethodManager.HIDE_IMPLICIT_ONLY);
And then later, if you wish to close it, in onPause() for example, you can call:
InputMethodManager imm = (InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(editText.getWindowToken(), 0);
The following code is pillaged from the Google's 4.1 source code for SearchView. Seems to work, fine on lesser versions of Android as well.
private Runnable mShowImeRunnable = new Runnable() {
public void run() {
InputMethodManager imm = (InputMethodManager) getContext()
.getSystemService(Context.INPUT_METHOD_SERVICE);
if (imm != null) {
imm.showSoftInput(editText, 0);
}
}
};
private void setImeVisibility(final boolean visible) {
if (visible) {
post(mShowImeRunnable);
} else {
removeCallbacks(mShowImeRunnable);
InputMethodManager imm = (InputMethodManager) getContext()
.getSystemService(Context.INPUT_METHOD_SERVICE);
if (imm != null) {
imm.hideSoftInputFromWindow(getWindowToken(), 0);
}
}
}
Then in addition, the following code needs to be added as the Control/Activity is created. (In my case it's a composite control, rather than an activity).
this.editText.setOnFocusChangeListener(new View.OnFocusChangeListener() {
public void onFocusChange(View v, boolean hasFocus) {
setImeVisibility(hasFocus);
}
});
android:windowSoftInputMode="stateAlwaysVisible" -> in manifest File.
edittext.requestFocus(); -> in code.
This will open soft keyboard on which edit-text has request focus as activity appears.
I have had some recent luck in some simple cases with the code
below. I haven't finished all testing but....
EditText input = (EditText) findViewById(R.id.Input);
input.requestFocus();
input.dispatchTouchEvent(MotionEvent.obtain(SystemClock.uptimeMillis(), SystemClock.uptimeMillis(), MotionEvent.ACTION_DOWN, 0f, 0f, 0));
input.dispatchTouchEvent(MotionEvent.obtain(SystemClock.uptimeMillis(), SystemClock.uptimeMillis(), MotionEvent.ACTION_UP, 0f, 0f, 0));
And presto the keyboard shows up.
You can try to force the soft keyboard to appear, it works for me:
...
dialog.show();
input.requestFocus();
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.toggleSoftInput(InputMethodManager.SHOW_FORCED, 0);
And for Kotlin just use this extensions:
fun EditText.showKeyboard() {
val imm = context.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
imm.showSoftInput(this, InputMethodManager.SHOW_IMPLICIT)
}
fun EditText.hideKeyboard() {
val imm = context.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
imm.hideSoftInputFromWindow(this.windowToken, 0)
}
For fragment, sure its working:
displayName = (EditText) view.findViewById(R.id.displayName);
InputMethodManager imm = (InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
imm.toggleSoftInput(InputMethodManager.SHOW_FORCED, 0);
Sometimes raukodraug's answer won't work. I've make it in this way with some trials and errors:
public static void showKeyboard(Activity activity) {
if (activity != null) {
activity.getWindow()
.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);
}
}
public static void hideKeyboard(Activity activity) {
if (activity != null) {
activity.getWindow()
.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
}
}
And the EditText part:
editText.setOnFocusChangeListener(new View.OnFocusChangeListener() {
#Override
public void onFocusChange(View v, boolean hasFocus) {
if (!hasFocus) {
hideKeyboard(getActivity());
} else {
showKeyboard(getActivity());
}
}
});
showSoftInput was not working for me at all.
I figured I needed to set the input mode: (here in the Activity component in the manifest)
android:windowSoftInputMode="stateVisible"
To hide keyboard, use this one:
getActivity().getWindow().setSoftInputMode(
WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
and to show keyboard:
getActivity().getWindow().setSoftInputMode(
WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);
Kotlin extension for showing the keyboard on focus.
This is a combination of previous responses, which where either too long or incomplete.
This extension posts a runnable on the message queue which shows the soft keyboard after requesting focus:
fun View.showSoftKeyboard() {
post {
if (this.requestFocus()) {
val imm = context.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
imm?.showSoftInput(this, InputMethodManager.SHOW_IMPLICIT)
}
}
}
Call it from any view when needed afterwards:
editText.showSoftKeyboard()
Simply add this line in your EditText view:
android:isScrollContainer="true"
and TADA - keyboard began to show up automatically!
I had similar problem and discovered this simple and strange solution.
As already was mentioned here by user3392439, appearance of the keyboard upon focus somehow wierdly connected with presense of the scroll component in the XML file.
Even presence of another EditText view which comprises abovementioned line in same XML makes keyboard appear no matter which one of EditTexts is currently focused.
If you have at least one visible view comprising scroll component in your XML file - keyboard will appear automatically on focus.
If no scroll - then you need to click on EditText to make keyboard appear.
Believe or not my problem with Soft Keyboard was resolved when I discovered that the Activities animations can disable the Soft Keyboard. When you call the intent with the
i.setFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
and
overridePendingTransition(0, 0);
It can hide the Soft Keyboard and there isn't a way to show it.
I had the same problem in various different situations, and the solutions i have found work in some but dont work in others so here is a combine solution that works in most situations i have found:
public static void showVirtualKeyboard(Context context, final View view) {
if (context != null) {
final InputMethodManager imm = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
view.clearFocus();
if(view.isShown()) {
imm.showSoftInput(view, 0);
view.requestFocus();
} else {
view.addOnAttachStateChangeListener(new View.OnAttachStateChangeListener() {
#Override
public void onViewAttachedToWindow(View v) {
view.post(new Runnable() {
#Override
public void run() {
view.requestFocus();
imm.showSoftInput(view, 0);
}
});
view.removeOnAttachStateChangeListener(this);
}
#Override
public void onViewDetachedFromWindow(View v) {
view.removeOnAttachStateChangeListener(this);
}
});
}
}
}
editText.post(new Runnable() {
#Override
public void run() {
InputMethodManager imm = (InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
imm.showSoftInput(editText, InputMethodManager.SHOW_IMPLICIT);
}
});
I combined everything here and for me it works:
public static void showKeyboardWithFocus(View v, Activity a) {
try {
v.requestFocus();
InputMethodManager imm = (InputMethodManager) a.getSystemService(Context.INPUT_METHOD_SERVICE);
imm.showSoftInput(v, InputMethodManager.SHOW_IMPLICIT);
a.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE);
} catch (Exception e) {
e.printStackTrace();
}
}
It worked for me. You can try with this also to show the keyboard:
getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);
code snippet . . .
public void hideKeyboard(Context activityContext){
InputMethodManager imm = (InputMethodManager)
activityContext.getSystemService(Context.INPUT_METHOD_SERVICE);
//android.R.id.content ( http://stackoverflow.com/a/12887919/2077479 )
View rootView = ((Activity) activityContext)
.findViewById(android.R.id.content).getRootView();
imm.hideSoftInputFromWindow(rootView.getWindowToken(), 0);
}
public void showKeyboard(Context activityContext, final EditText editText){
final InputMethodManager imm = (InputMethodManager)
activityContext.getSystemService(Context.INPUT_METHOD_SERVICE);
if (!editText.hasFocus()) {
editText.requestFocus();
}
editText.post(new Runnable() {
#Override
public void run() {
imm.showSoftInput(editText, InputMethodManager.SHOW_FORCED);
}
});
}
Inside your manifest:
android:windowSoftInputMode="stateAlwaysVisible" - initially launched keyboard.
android:windowSoftInputMode="stateAlwaysHidden" - initially hidden keyboard.
I like to use also "adjustPan" because when the keyboard launches then the screen auto adjusts.
<activity
android:name="YourActivity"
android:windowSoftInputMode="stateAlwaysHidden|adjustPan"/>
Here's a more reliable solution i got from Square:
fun View.focusAndShowKeyboard() {
/**
* This is to be called when the window already has focus.
*/
fun View.showTheKeyboardNow() {
if (isFocused) {
post {
// We still post the call, just in case we are being notified of the windows focus
// but InputMethodManager didn't get properly setup yet.
val imm = context.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
imm.showSoftInput(this, InputMethodManager.SHOW_IMPLICIT)
}
}
}
requestFocus()
if (hasWindowFocus()) {
// No need to wait for the window to get focus.
showTheKeyboardNow()
} else {
// We need to wait until the window gets focus.
viewTreeObserver.addOnWindowFocusChangeListener(
object : ViewTreeObserver.OnWindowFocusChangeListener {
override fun onWindowFocusChanged(hasFocus: Boolean) {
// This notification will arrive just before the InputMethodManager gets set up.
if (hasFocus) {
this#focusAndShowKeyboard.showTheKeyboardNow()
// It’s very important to remove this listener once we are done.
viewTreeObserver.removeOnWindowFocusChangeListener(this)
}
}
})
}
}
Code credits from here.
just add android:windowSoftInputMode="stateHidden" in manifest file...
final InputMethodManager keyboard = (InputMethodManager) ctx.getSystemService(Context.INPUT_METHOD_SERVICE);
keyboard.toggleSoftInput(InputMethodManager.SHOW_FORCED,0);
None of the Answers worked for me. Here is a simple way.
searchEditText.setVisibility(View.VISIBLE);
final Handler handler=new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
searchEditText.requestFocus();
}
}, 400);
Just delayed the requestFocus() method for 400ms.
All solutions given above (InputMethodManager interaction in OnFocusChangeListener.onFocusChange listener attached to your EditText works fine if you have single edit in the activity.
In my case I have two edits.
private EditText tvX, tvY;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
tvX.setOnFocusChangeListener(this);
tvY.setOnFocusChangeListener(this);
#Override
public void onFocusChange(View v, boolean hasFocus) {
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
if(tvX.hasFocus() || tvY.hasFocus()) {
imm.showSoftInput(v, 0);
} else {
imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
}
};
I have observed that onFocusChange is triggered for tvX with hasFocus=true (keyboard shown) but then for tvY with hasFocus=true (keyboard hidden). In the end, no keyboard was visible.
General solution should have correct statement in if "show keyboard if EditText text has focus"
In your onResume() section of the Activity you can do call the method bringKeyboard();
onResume() {
EditText yourEditText= (EditText) findViewById(R.id.yourEditText);
bringKeyboard(yourEditText);
}
protected boolean bringKeyboard(EditText view) {
if (view == null) {
return false;
}
try {
// Depending if edittext has some pre-filled values you can decide whether to bring up soft keyboard or not
String value = view.getText().toString();
if (value == null) {
InputMethodManager imm = (InputMethodManager)context.getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
return true;
}
} catch (Exception e) {
Log.e(TAG, "decideFocus. Exception", e);
}
return false;
}
As I read on the official document, I think this is the best answer, just pass the View to parameter such as your EditText, but showSoftKeyboard seems like not working on landscape
private fun showSoftKeyboard(view: View) {
if (view.requestFocus()) {
val imm = getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
imm.showSoftInput(view, InputMethodManager.SHOW_IMPLICIT)
}
}
private fun closeSoftKeyboard(view: View) {
if (view.requestFocus()) {
val imm = getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
imm.hideSoftInputFromWindow(view.windowToken, InputMethodManager.HIDE_NOT_ALWAYS)
}
}
For Kotlin:
val imm = context.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
fun showKeyboard() {
imm.toggleSoftInput(InputMethodManager.SHOW_FORCED, 0)
}
fun hideKeyboard() {
imm.hideSoftInputFromWindow(phoneNoInputTxt.windowToken, 0);
}
Then just call what you want!

Hide soft input keyboard when dialog closes

I'm opening a Dialog from within an Activity. When the dialog opens, I call
((InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE)).toggleSoftInput(InputMethodManager.SHOW_FORCED, InputMethodManager.HIDE_IMPLICIT_ONLY);
The problem is, when I close the dialog either by hitting a cancel button or clicking outside the dialog, the keyboard switches to a text keyboard and doesn't go away util I click the hardware back button. How can I dismiss the keyboard when the dialog is dismissed, and focus is returned to the previous window?
in AndroidManifest.xml, set this property in your Activity that show the Dialog
android:windowSoftInputMode="stateAlwaysHidden"
Note! not stateHiddent, is stateAlwaysHidden. It will automatically hide soft keyboard on Dismiss of Dialog.
Hope that save your life.
I guess that this method of the activity can be useful to you.
#Override
public void onWindowFocusChanged(boolean hasFocus) {
// TODO Auto-generated method stub
super.onWindowFocusChanged(hasFocus);
if(hasFocus)
{
Toast.makeText(MainActivity.this, "has focus", Toast.LENGTH_LONG).show();
// write code to remove keyboard
}
}
AlertDialog.Builder builder = new AlertDialog.Builder(EllipticalActivity.this);
builder.setTitle("title")
.setMessage("message")
.setCancelable(false)
.setNegativeButton("Close", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
InputMethodManager inputManager =
(InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
inputManager.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(),
InputMethodManager.HIDE_NOT_ALWAYS);
dialog.cancel();
}
});
AlertDialog alert = builder.create();
alert.show();
In my case, solution was to put keyboard hide in dialog dismiss
dialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
#Override
public void onDismiss(DialogInterface dialog) {
View view = activity.getCurrentFocus();
if (view != null) {
InputMethodManager inputManager = (InputMethodManager) activity.getSystemService(Context.INPUT_METHOD_SERVICE);
inputManager.hideSoftInputFromWindow(view.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
}
}
});
From Activity onCreateView() method you can do this:
getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN)
Or In Manifest xml
android:windowSoftInputMode="stateAlwaysHidden"
It will automatically hide soft keyboard on Dismiss of Dialog

How to show soft-keyboard when edittext is focused

I want to automatically show the soft-keyboard when an EditText is focused (if the device does not have a physical keyboard) and I have two problems:
When my Activity is displayed, my EditText is focused but the keyboard is not displayed, I need to click again on it to show the keyboard (it should be displayed when my Activity is displayed).
And when I click done on the keyboard, the keyboard is dissmissed but the EditText stays focused and y don't want (because my edit is done).
To resume, my problem is to have something more like on the iPhone: which keep the keyboard sync with my EditText state (focused / not focused) and of course does not present a soft-keyboard if there is a physical one.
To force the soft keyboard to appear, you can use
EditText yourEditText= (EditText) findViewById(R.id.yourEditText);
yourEditText.requestFocus();
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.showSoftInput(yourEditText, InputMethodManager.SHOW_IMPLICIT);
And for removing the focus on EditText, sadly you need to have a dummy View to grab focus.
To close it you can use
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(yourEditText.getWindowToken(), 0);
This works for using it in a dialog
public void showKeyboard(){
InputMethodManager inputMethodManager = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
inputMethodManager.toggleSoftInput(InputMethodManager.SHOW_FORCED, 0);
}
public void closeKeyboard(){
InputMethodManager inputMethodManager = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
inputMethodManager.toggleSoftInput(InputMethodManager.HIDE_IMPLICIT_ONLY, 0);
}
I had the same problem. Immediately after editText VISIBILITY change from GONE to VISIBLE, I had to set the focus and display the soft keyboard. I achieved this using the following code:
new Handler().postDelayed(new Runnable() {
public void run() {
// ((EditText) findViewById(R.id.et_find)).requestFocus();
//
EditText yourEditText= (EditText) findViewById(R.id.et_find);
// InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
// imm.showSoftInput(yourEditText, InputMethodManager.SHOW_IMPLICIT);
yourEditText.dispatchTouchEvent(MotionEvent.obtain(SystemClock.uptimeMillis(), SystemClock.uptimeMillis(), MotionEvent.ACTION_DOWN, 0f, 0f, 0));
yourEditText.dispatchTouchEvent(MotionEvent.obtain(SystemClock.uptimeMillis(), SystemClock.uptimeMillis(), MotionEvent.ACTION_UP, 0f, 0f, 0));
}
}, 200);
It works for me with 100ms delay, but failed without any delay or with only a delay of 1ms.
Commented part of code shows another approach, which works only on some devices. I tested on OS versions 2.2 (emulator), 2.2.1 (real device) and 1.6 (emulator).
This approach saved me a lot of pain.
To cause the keyboard to appear, use
getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE);
This method is more reliable than invoking the InputMethodManager directly.
To close it, use
getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);
When nothing else works, force it to be shown:
editText.requestFocus();
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.toggleSoftInput(InputMethodManager.SHOW_FORCED, InputMethodManager.HIDE_IMPLICIT_ONLY);
And then later, if you wish to close it, in onPause() for example, you can call:
InputMethodManager imm = (InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(editText.getWindowToken(), 0);
The following code is pillaged from the Google's 4.1 source code for SearchView. Seems to work, fine on lesser versions of Android as well.
private Runnable mShowImeRunnable = new Runnable() {
public void run() {
InputMethodManager imm = (InputMethodManager) getContext()
.getSystemService(Context.INPUT_METHOD_SERVICE);
if (imm != null) {
imm.showSoftInput(editText, 0);
}
}
};
private void setImeVisibility(final boolean visible) {
if (visible) {
post(mShowImeRunnable);
} else {
removeCallbacks(mShowImeRunnable);
InputMethodManager imm = (InputMethodManager) getContext()
.getSystemService(Context.INPUT_METHOD_SERVICE);
if (imm != null) {
imm.hideSoftInputFromWindow(getWindowToken(), 0);
}
}
}
Then in addition, the following code needs to be added as the Control/Activity is created. (In my case it's a composite control, rather than an activity).
this.editText.setOnFocusChangeListener(new View.OnFocusChangeListener() {
public void onFocusChange(View v, boolean hasFocus) {
setImeVisibility(hasFocus);
}
});
android:windowSoftInputMode="stateAlwaysVisible" -> in manifest File.
edittext.requestFocus(); -> in code.
This will open soft keyboard on which edit-text has request focus as activity appears.
I have had some recent luck in some simple cases with the code
below. I haven't finished all testing but....
EditText input = (EditText) findViewById(R.id.Input);
input.requestFocus();
input.dispatchTouchEvent(MotionEvent.obtain(SystemClock.uptimeMillis(), SystemClock.uptimeMillis(), MotionEvent.ACTION_DOWN, 0f, 0f, 0));
input.dispatchTouchEvent(MotionEvent.obtain(SystemClock.uptimeMillis(), SystemClock.uptimeMillis(), MotionEvent.ACTION_UP, 0f, 0f, 0));
And presto the keyboard shows up.
You can try to force the soft keyboard to appear, it works for me:
...
dialog.show();
input.requestFocus();
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.toggleSoftInput(InputMethodManager.SHOW_FORCED, 0);
And for Kotlin just use this extensions:
fun EditText.showKeyboard() {
val imm = context.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
imm.showSoftInput(this, InputMethodManager.SHOW_IMPLICIT)
}
fun EditText.hideKeyboard() {
val imm = context.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
imm.hideSoftInputFromWindow(this.windowToken, 0)
}
For fragment, sure its working:
displayName = (EditText) view.findViewById(R.id.displayName);
InputMethodManager imm = (InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
imm.toggleSoftInput(InputMethodManager.SHOW_FORCED, 0);
Sometimes raukodraug's answer won't work. I've make it in this way with some trials and errors:
public static void showKeyboard(Activity activity) {
if (activity != null) {
activity.getWindow()
.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);
}
}
public static void hideKeyboard(Activity activity) {
if (activity != null) {
activity.getWindow()
.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
}
}
And the EditText part:
editText.setOnFocusChangeListener(new View.OnFocusChangeListener() {
#Override
public void onFocusChange(View v, boolean hasFocus) {
if (!hasFocus) {
hideKeyboard(getActivity());
} else {
showKeyboard(getActivity());
}
}
});
showSoftInput was not working for me at all.
I figured I needed to set the input mode: (here in the Activity component in the manifest)
android:windowSoftInputMode="stateVisible"
To hide keyboard, use this one:
getActivity().getWindow().setSoftInputMode(
WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
and to show keyboard:
getActivity().getWindow().setSoftInputMode(
WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);
Kotlin extension for showing the keyboard on focus.
This is a combination of previous responses, which where either too long or incomplete.
This extension posts a runnable on the message queue which shows the soft keyboard after requesting focus:
fun View.showSoftKeyboard() {
post {
if (this.requestFocus()) {
val imm = context.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
imm?.showSoftInput(this, InputMethodManager.SHOW_IMPLICIT)
}
}
}
Call it from any view when needed afterwards:
editText.showSoftKeyboard()
Simply add this line in your EditText view:
android:isScrollContainer="true"
and TADA - keyboard began to show up automatically!
I had similar problem and discovered this simple and strange solution.
As already was mentioned here by user3392439, appearance of the keyboard upon focus somehow wierdly connected with presense of the scroll component in the XML file.
Even presence of another EditText view which comprises abovementioned line in same XML makes keyboard appear no matter which one of EditTexts is currently focused.
If you have at least one visible view comprising scroll component in your XML file - keyboard will appear automatically on focus.
If no scroll - then you need to click on EditText to make keyboard appear.
Believe or not my problem with Soft Keyboard was resolved when I discovered that the Activities animations can disable the Soft Keyboard. When you call the intent with the
i.setFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
and
overridePendingTransition(0, 0);
It can hide the Soft Keyboard and there isn't a way to show it.
I had the same problem in various different situations, and the solutions i have found work in some but dont work in others so here is a combine solution that works in most situations i have found:
public static void showVirtualKeyboard(Context context, final View view) {
if (context != null) {
final InputMethodManager imm = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
view.clearFocus();
if(view.isShown()) {
imm.showSoftInput(view, 0);
view.requestFocus();
} else {
view.addOnAttachStateChangeListener(new View.OnAttachStateChangeListener() {
#Override
public void onViewAttachedToWindow(View v) {
view.post(new Runnable() {
#Override
public void run() {
view.requestFocus();
imm.showSoftInput(view, 0);
}
});
view.removeOnAttachStateChangeListener(this);
}
#Override
public void onViewDetachedFromWindow(View v) {
view.removeOnAttachStateChangeListener(this);
}
});
}
}
}
editText.post(new Runnable() {
#Override
public void run() {
InputMethodManager imm = (InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
imm.showSoftInput(editText, InputMethodManager.SHOW_IMPLICIT);
}
});
I combined everything here and for me it works:
public static void showKeyboardWithFocus(View v, Activity a) {
try {
v.requestFocus();
InputMethodManager imm = (InputMethodManager) a.getSystemService(Context.INPUT_METHOD_SERVICE);
imm.showSoftInput(v, InputMethodManager.SHOW_IMPLICIT);
a.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE);
} catch (Exception e) {
e.printStackTrace();
}
}
It worked for me. You can try with this also to show the keyboard:
getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);
code snippet . . .
public void hideKeyboard(Context activityContext){
InputMethodManager imm = (InputMethodManager)
activityContext.getSystemService(Context.INPUT_METHOD_SERVICE);
//android.R.id.content ( http://stackoverflow.com/a/12887919/2077479 )
View rootView = ((Activity) activityContext)
.findViewById(android.R.id.content).getRootView();
imm.hideSoftInputFromWindow(rootView.getWindowToken(), 0);
}
public void showKeyboard(Context activityContext, final EditText editText){
final InputMethodManager imm = (InputMethodManager)
activityContext.getSystemService(Context.INPUT_METHOD_SERVICE);
if (!editText.hasFocus()) {
editText.requestFocus();
}
editText.post(new Runnable() {
#Override
public void run() {
imm.showSoftInput(editText, InputMethodManager.SHOW_FORCED);
}
});
}
Inside your manifest:
android:windowSoftInputMode="stateAlwaysVisible" - initially launched keyboard.
android:windowSoftInputMode="stateAlwaysHidden" - initially hidden keyboard.
I like to use also "adjustPan" because when the keyboard launches then the screen auto adjusts.
<activity
android:name="YourActivity"
android:windowSoftInputMode="stateAlwaysHidden|adjustPan"/>
Here's a more reliable solution i got from Square:
fun View.focusAndShowKeyboard() {
/**
* This is to be called when the window already has focus.
*/
fun View.showTheKeyboardNow() {
if (isFocused) {
post {
// We still post the call, just in case we are being notified of the windows focus
// but InputMethodManager didn't get properly setup yet.
val imm = context.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
imm.showSoftInput(this, InputMethodManager.SHOW_IMPLICIT)
}
}
}
requestFocus()
if (hasWindowFocus()) {
// No need to wait for the window to get focus.
showTheKeyboardNow()
} else {
// We need to wait until the window gets focus.
viewTreeObserver.addOnWindowFocusChangeListener(
object : ViewTreeObserver.OnWindowFocusChangeListener {
override fun onWindowFocusChanged(hasFocus: Boolean) {
// This notification will arrive just before the InputMethodManager gets set up.
if (hasFocus) {
this#focusAndShowKeyboard.showTheKeyboardNow()
// It’s very important to remove this listener once we are done.
viewTreeObserver.removeOnWindowFocusChangeListener(this)
}
}
})
}
}
Code credits from here.
just add android:windowSoftInputMode="stateHidden" in manifest file...
final InputMethodManager keyboard = (InputMethodManager) ctx.getSystemService(Context.INPUT_METHOD_SERVICE);
keyboard.toggleSoftInput(InputMethodManager.SHOW_FORCED,0);
None of the Answers worked for me. Here is a simple way.
searchEditText.setVisibility(View.VISIBLE);
final Handler handler=new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
searchEditText.requestFocus();
}
}, 400);
Just delayed the requestFocus() method for 400ms.
All solutions given above (InputMethodManager interaction in OnFocusChangeListener.onFocusChange listener attached to your EditText works fine if you have single edit in the activity.
In my case I have two edits.
private EditText tvX, tvY;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
tvX.setOnFocusChangeListener(this);
tvY.setOnFocusChangeListener(this);
#Override
public void onFocusChange(View v, boolean hasFocus) {
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
if(tvX.hasFocus() || tvY.hasFocus()) {
imm.showSoftInput(v, 0);
} else {
imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
}
};
I have observed that onFocusChange is triggered for tvX with hasFocus=true (keyboard shown) but then for tvY with hasFocus=true (keyboard hidden). In the end, no keyboard was visible.
General solution should have correct statement in if "show keyboard if EditText text has focus"
In your onResume() section of the Activity you can do call the method bringKeyboard();
onResume() {
EditText yourEditText= (EditText) findViewById(R.id.yourEditText);
bringKeyboard(yourEditText);
}
protected boolean bringKeyboard(EditText view) {
if (view == null) {
return false;
}
try {
// Depending if edittext has some pre-filled values you can decide whether to bring up soft keyboard or not
String value = view.getText().toString();
if (value == null) {
InputMethodManager imm = (InputMethodManager)context.getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
return true;
}
} catch (Exception e) {
Log.e(TAG, "decideFocus. Exception", e);
}
return false;
}
As I read on the official document, I think this is the best answer, just pass the View to parameter such as your EditText, but showSoftKeyboard seems like not working on landscape
private fun showSoftKeyboard(view: View) {
if (view.requestFocus()) {
val imm = getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
imm.showSoftInput(view, InputMethodManager.SHOW_IMPLICIT)
}
}
private fun closeSoftKeyboard(view: View) {
if (view.requestFocus()) {
val imm = getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
imm.hideSoftInputFromWindow(view.windowToken, InputMethodManager.HIDE_NOT_ALWAYS)
}
}
For Kotlin:
val imm = context.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
fun showKeyboard() {
imm.toggleSoftInput(InputMethodManager.SHOW_FORCED, 0)
}
fun hideKeyboard() {
imm.hideSoftInputFromWindow(phoneNoInputTxt.windowToken, 0);
}
Then just call what you want!

force dialog input to require fullscreen ime soft keyboard in landscape

I have a dialog box with an input, I have to automatically pop up the soft keyboard, current code:
final EditText input = new EditText(this);
final AlertDialog dialog = new AlertDialog.Builder(ScActivity.this)
.setMessage(message)
.setView(input).setPositiveButton("Ok", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(input.getWindowToken(), 0);
// do positive stuff
}
}).setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(input.getWindowToken(), 0);
}
}).create();
input.setOnFocusChangeListener(new View.OnFocusChangeListener() {
#Override
public void onFocusChange(View v, boolean hasFocus) {
if (hasFocus) {
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.toggleSoftInput(InputMethodManager.SHOW_FORCED,
InputMethodManager.HIDE_IMPLICIT_ONLY);
}
}
});
dialog.show();
input.requestFocus();
This works fine, except for one behavior. The first time I show this window in landscape the mode, the dialog box jumps up, as if it's trying to make room for the soft keyboard, then realizes there isn't enough room, jumps back down, then the fullscreen ime keyboard shows (with the text input).
It looks like a glitch. Don't want to live with it. Have tried doing things in different order, doing things on timers. Every consecutive time after the first, the keyboard shows up on top, no jumping. Anyone know of any workaround? I just want the soft keyboard to show up on top, fullscreen, in landscape mode (portrait mode has enough room for the dialog box to move up and be visible.
Thanks

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

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.
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);
}
}
});
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);
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);
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);
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();
<activity
...
android:windowSoftInputMode="stateVisible" >
</activity>
or
getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE);
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;
}
}
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);
}
});
}
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);
}
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);
}
}
});
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.
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);
}
}
});
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);
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)
}
}
}
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);
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)
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();
}
}
}
try and use:
editText.requestFocus();
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.toggleSoftInput(InputMethodManager.SHOW_FORCED, InputMethodManager.HIDE_IMPLICIT_ONLY);
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);
getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);
I call this in onCreate() to show keyboard automatically, when I came in the Activity.
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);
}
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)
}
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()
just add this line to manifest file necessary activity.
android:windowSoftInputMode="stateVisible"
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>
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:
Make the parent view(content view of your activity) clickable and focusable by adding the following attributes
android:clickable="true"
android:focusableInTouchMode="true"
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 );
}
Lastly, set the onFocusChangeListener of your edittext.
edittext.setOnFocusChangeListener(new View.OnFocusChangeListener() {
#Override
public void onFocusChange(View v, boolean hasFocus) {
if (!hasFocus) {
hideKeyboard(v);
}
}
});
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);
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);
}
Looking at https://stackoverflow.com/a/39144104/2914140 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://stackoverflow.com/a/11155404/2914140:
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.
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.

Categories

Resources