How to dismiss android keyboard on dialog dismiss? - android

I have a dialog box open in my android app, and I have a button when clicked will dismiss the dialog box. The problem is there is also a textedit field, and if its focused and the keyboard is showing, then when I click the cancel button, then dialog goes away, but the keyboard is still showing.
I want to also dismiss the keyboard.
I was searching around, and for threads like this
Hide soft keyboard after dialog dismiss
But none of the solutions worked for me. By the way the edittext is a number input type, if that makes a difference somehow.
Does anyone know how to fix this?
Thanks
public void HandleTeamManagement() {
final Dialog teamDialog = new Dialog(this);
teamDialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
teamDialog.setContentView(R.layout.dialog_team_management);
final EditText mergeNum = (EditText) teamDialog.findViewById(R.id.group);
InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(mergeNum.getWindowToken(), 0);
// Setting Negative "NO" Button
Button cancelButton = (Button) teamDialog.findViewById(R.id.cancel);
cancelButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
teamDialog.dismiss();
}
});
// Showing Alert Dialog
teamDialog.show();
}

You can find a solution here:
http://www.workingfromhere.com/blog/2011/04/27/close-hide-the-android-soft-keyboard/
Close/hide the Android Soft Keyboard
Edited: adding code
Try this ..it worked for me
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
if (editText!= null && getActivity() != null) {
InputMethodManager imm = (InputMethodManager) getActivity()
.getSystemService(
Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(
editText.getWindowToken(), 0);
}
}
}, 1000);

Related

Soft keyboard appears after Dialog is closed

Every time I have focus on some edit field and Dialog shows up, it will pull up soft keyboard as soon as I dismiss(); Dialog. I have tried every way to remove it after click event, but whatever I do it still shows up.
public static void hideSoftInput(FragmentActivity _activity){
if(_activity.getCurrentFocus() != null){
InputMethodManager inputManager = (InputMethodManager) _activity.getSystemService(Context.INPUT_METHOD_SERVICE);
inputManager.hideSoftInputFromWindow(_activity.getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
}
}
public static void hideSoftInput(View _v, Context _c){
if(_v.getWindowToken() != null){
InputMethodManager inputManager = (InputMethodManager) _c.getSystemService(Context.INPUT_METHOD_SERVICE);
inputManager.hideSoftInputFromWindow(_v.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
}
}
I can't find it now but someone else on here suggested to wrap the call to hide the keyboard in a postDelayed call.
It worked for me when many other options failed. The only thing is that it may give a funny jiggle of the screen because you will be suppressing the keyboard while it is trying to show. Without the postDelayed it seems it will try to hide the keyboard before Android tries to show it after the dialog has closed. So ultimately we have to fight a timing issue in Android.
Something like this:
view.postDelayed(new Runnable()
{
#Override
public void run()
{
hideKeyboard();
}
}, 50);

Android: How to open keyboard for editing EditText when click button?

my case is: I have one EditText field that is with disabled focus.
Beside EditText field I has two buttons for Input methods. So I want when click first button: to open soft keybord and edit text in EditText field. I try many ways with:
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.showSoftInput(yourEditText, InputMethodManager.SHOW_IMPLICIT);
and doesn't work for me. Only way to open soft keyboard is:
toggleSoftInput(InputMethodManager.SHOW_FORCED, 0)
but there is no way to edit info from EditText field.
May you suggest me how to open keyboard and edit text for some EditText when click button.
Thanks a lot!
Edited:
So, EditText is not focusable be default. When I click Keyboard button - should be focusable, then show me soft keyboard to enter text and appear in EditText. Other method to insert is A-B-C button which not required keyboard. It will be something like Morse code input - touch and hold A-B-C button :) I'll try suggested example to implement in my case. Thank you guys :)
Thanks guys for your help :) I used all suggestions that you gave me, searched and tested a lot of other scripts and finally my code is working :)
Here is my final code:
InputEditText = (EditText) findViewById(R.id.InputText);
public void InputData() {
/* Keyboard Button Action */
KeyboardButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Log.v(TAG, "On Keyboard Button click event!");
InputEditText.requestFocus();
InputEditText.setFocusableInTouchMode(true);
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.showSoftInput(InputEditText, InputMethodManager.SHOW_FORCED);
}
});
}
It may be useful for someone :)
Thank you!
The design you've described isn't recommended. You're violating the focusable attribute's purpose which is not to control whether the user can alter the text in a EditText component.
If you plan to provide an alternative input method because the use case seems to require this (e.g. you allow only a certain set of symbols in the editable text field) then you should probably disable text editing altogether for the time the user isn't allowed to change the value of the field.
Declare your editable field:
<EditText
android:id="#+id/edit_text_2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10" />
notice that its focusable attribute is left with the default value. That's ok, we'll handle that later. Declare a button which will start editing process:
<Button
android:id="#+id/button_show_ime"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Start editing" />
Now, in your Activity declare:
private EditText editText2;
private KeyListener originalKeyListener;
private Button buttonShowIme;
And in onCreate() do this:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.ime_activity);
// Find out our editable field.
editText2 = (EditText)findViewById(R.id.edit_text_2);
// Save its key listener which makes it editable.
originalKeyListener = editText2.getKeyListener();
// Set it to null - this will make the field non-editable
editText2.setKeyListener(null);
// Find the button which will start editing process.
buttonShowIme = (Button)findViewById(R.id.button_show_ime);
// Attach an on-click listener.
buttonShowIme.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// Restore key listener - this will make the field editable again.
editText2.setKeyListener(originalKeyListener);
// Focus the field.
editText2.requestFocus();
// Show soft keyboard for the user to enter the value.
InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
imm.showSoftInput(editText2, InputMethodManager.SHOW_IMPLICIT);
}
});
// We also want to disable editing when the user exits the field.
// This will make the button the only non-programmatic way of editing it.
editText2.setOnFocusChangeListener(new View.OnFocusChangeListener() {
#Override
public void onFocusChange(View v, boolean hasFocus) {
// If it loses focus...
if (!hasFocus) {
// Hide soft keyboard.
InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(editText2.getWindowToken(), 0);
// Make it non-editable again.
editText2.setKeyListener(null);
}
}
});
}
I hope the code with all the comments is self-explanatory. Tested on APIs 8 and 17.
Try this :
final EditText myedit2 = (EditText) findViewById(R.id.myEditText2);
Button btsmall = (Button) findViewById(R.id.BtSmall);
btsmall.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
myedit2.requestFocus();
}
});
I Have Work this code for open a keybord when button click.
Like .
btn1 = (Button) findViewById(R.id.btn1);
edt1 = (EditText) findViewById(R.id.edt1);
btn1.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
edt1.requestFocus();
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.showSoftInput(edt1, InputMethodManager.SHOW_IMPLICIT);
}
});
its completed work.
LinearLayout ll_about_me =(LinearLayout) view.findViewById(R.id.ll_about_me);
ll_about_me.setOnTouchListener(new OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
// TODO Auto-generated method stub
mEtEmpAboutYou.requestFocus();
mEtEmpAboutYou.setFocusableInTouchMode(true);
InputMethodManager imm = (InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
imm.showSoftInput(mEtEmpAboutYou, InputMethodManager.SHOW_FORCED);
return true;
}
});
For those that uses fragments you can use InputMethodManager that way:
InputMethodManager imm = (InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
if (imm != null) {
imm.showSoftInput(editText, InputMethodManager.SHOW_FORCED);
}
Full Code:
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
editText.setFocusable(true);
editText.setFocusableInTouchMode(true);
editText.requestFocus();
InputMethodManager imm = (InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
if (imm != null) {
imm.showSoftInput(editText, InputMethodManager.SHOW_FORCED);
}
}
});
I hope this help
EditText txt_categorie = findViewById(R.id.txt_categorie);
txt_categorie.requestFocus();

hiding keyboard issue

I am using the following code to hide the keyboard when a button is clicked:
private OnClickListener saveButtonListener = new OnClickListener() {
#Override
public void onClick(View v) {
final View activityRootView = findViewById(R.id.myProfileDetails);
activityRootView.getViewTreeObserver().addOnGlobalLayoutListener(new OnGlobalLayoutListener() {
#Override
public void onGlobalLayout() {
int heightDiff = activityRootView.getRootView().getHeight() - activityRootView.getHeight();
if (heightDiff > 100) { // if more than 100 pixels, its probably a keyboard...
imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.toggleSoftInput(InputMethodManager.HIDE_IMPLICIT_ONLY, 0);
}
}
});
//other code that does something
}
}
The button also does some other things but none of it is related to the keyboard and on pressing the button, the activity does not change.
I also have two EditText fields in my activity. When I am using the application and i tap on either field, they gain focus and the keyboard appears. When I press the button, the keyboard disappears and the other code is executed exactly as it should be. In this instance, everything is perfect.
The problem arises when tap on either EditText field for the second time. Now, the EditText gains focus but the keyboard appears and disappears almost instantly without me doing anything. I am guessing my code makes the keyboard disappear permanently after the first time I click the button. Why is this happening and how can I correct this?
you are initializing a ClickListener in your OnClick. which will hide the keyboard as soon as heightDiff>100. Do not do this.
do like this
private OnClickListener saveButtonListener = new OnClickListener() {
#Override
public void onClick(View v) {
imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(
editText.getWindowToken(), 0);
//other code that does something
}
}

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

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