Hide and Show the Soft Keyboard - simultaneously - android

If I may to ask almost the same question here from this topic
I've added in my activity_main.xml file:
android:focusable="true"
android:focusableInTouchMode="true"
activity_main.xml:
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:focusable="true"
android:focusableInTouchMode="true"
tools:context="com.example.stefancvetkovic.stefantest001.MainActivity">
<EditText
android:id="#+id/txtScanedResult"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:ems="10"
android:inputType="textPersonName"
tools:layout_editor_absoluteX="16dp"
tools:layout_editor_absoluteY="16dp" />
</android.support.constraint.ConstraintLayout>
And it works fine, but when I want to hide my keyboard on finish event, the keyboard stays opened.
MainActivity.java:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
((EditText)findViewById(R.id.txtScanedResult)).setOnEditorActionListener(
new EditText.OnEditorActionListener() {
#Override
public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
if (actionId == EditorInfo.IME_ACTION_SEARCH ||
actionId == EditorInfo.IME_ACTION_DONE ||
event != null &&
event.getAction() == KeyEvent.ACTION_DOWN &&
event.getKeyCode() == KeyEvent.KEYCODE_ENTER) {
if (event == null || !event.isShiftPressed()) {
// the user is done typing.
//HIDE KEYBOARD
EditText edtView=(EditText)findViewById(R.id.txtScanedResult);
edtView.setInputType((InputType.TYPE_NULL));
//
Toast.makeText(getApplicationContext(),"Voila!",Toast.LENGTH_SHORT)
.show();
return true; // consume.
}
}
return false; // pass on to other listeners.
}
});
}
Toast works perfectly on finish event, but keyboard stays opened.
Hoiw can I manage to be initialy closed keyboard on the load, and to be hidden on finishEvent?
I am running in emulator on Android 5.1

Try this one
/**
* This function is used to hide soft keyboard
*
* #param context mContext
* #param view view for which keyboard is open
*/
public static void hideSoftInput(Context context, View view) {
if (view != null) {
InputMethodManager inputMethodManager = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
if (!inputMethodManager.isActive()) {
return;
}
inputMethodManager.hideSoftInputFromWindow(view.getWindowToken(), 0);
}
}
/**
* This function is used to hide soft keyboard
*
* #param activity activity
*/
public static void hideSoftInput(Activity activity) {
try {
if (activity != null) {
View focusedView = activity.getCurrentFocus();
hideSoftInput(activity, focusedView);
}
} catch (Throwable t) {
CustomLogHandler.printErrorlog(t);
}
}
/**
* This function is used to show soft keyboard
*
* #param activity activity
*/
public static void showSoftInput(Activity activity) {
try {
if (activity != null) {
View focusedView = activity.getCurrentFocus();
if (focusedView != null) {
InputMethodManager inputMethodManager = (InputMethodManager) activity.getSystemService(Context.INPUT_METHOD_SERVICE);
inputMethodManager.showSoftInput(focusedView, InputMethodManager.SHOW_IMPLICIT);
}
}
} catch (Throwable t) {
CustomLogHandler.printErrorlog(t);
}
}
/**
* This function is used to show soft keyboard
*
* #param view view for which soft keyboard need to be opened
*/
public static void showSoftInput(final View view) {
try {
if (view == null) {
return;
}
view.requestFocus();
InputMethodManager inputManager = (InputMethodManager) view.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
inputManager.showSoftInput(view, 0);
} catch (Exception e) {
CustomLogHandler.printErrorlog(e);
}
}
or try
getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);

Call it before showing toast.
public void hideKeyboard(Activity context) {
// Check if no view has focus:
View view = context.getCurrentFocus();
if (view != null) {
InputMethodManager inputManager = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
inputManager.hideSoftInputFromWindow(view.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
}
}

Try this code:
/**
* Hides the soft keyboard
*/
public void hideSoftKeyboard() {
if(getCurrentFocus()!=null) {
InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);
inputMethodManager.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), 0);
}
}
/**
* Shows the soft keyboard
*/
public void showSoftKeyboard(View view) {
InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);
view.requestFocus();
inputMethodManager.showSoftInput(view, 0);
}
or do this:
In the AndroidManifest.xml:
<activity android:name="com.your.package.ActivityName"
android:windowSoftInputMode="stateHidden" />
or try:
getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN)‌​;

Related

Hide to show and hide keyboard in DialogFragment

In my dialog fragment, I am able to show the keyboard using
getDialog().getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT STATE_VISIBLE);
but I am not able to hide it on dismiss.
I've tried
getDialog().getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);
and
getDialog().getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
neither of which work.
I've also tried showing and hiding the keyboard using
InputMethodManager inputManager = (InputMethodManager)context.getSystemService(Context.INPUT_METHOD_SERVICE);
inputManager.toggleSoftInput(0, 0);
and
InputMethodManager inputManager = (InputMethodManager)context.getSystemService(Context.INPUT_METHOD_SERVICE);
inputManager.hideSoftInputFromWindow(view.getWindowToken(), 0);
but these are not able to show or hide the keyboard.
public static class MyDialogFragment extends DialogFragment
{
#Nullable #Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
return inflater.inflate(R.layout.my_input_dialog, container, false);
}
#Override
public void onViewCreated(View v, Bundle savedInstanceState)
{
super.onViewCreated(v, savedInstanceState);
final EditText editText = (EditText)v.findViewById(R.id.input);
// this line below is able to show the keyboard
getDialog().getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE);
Button add = (Button)v.findViewById(R.id.add_btn);
add.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
// other code not shown
dismiss();
}
});
Button cancel = (Button)v.findViewById(R.id.cancel_btn);
cancelButton.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
dismiss();
}
});
}
#Override
public void onDismiss(DialogInterface dialog)
{
//this line below does NOT work, it does not hide the keyboard
getDialog().getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);
super.onDismiss(dialog);
}
}
Note: I have read these stackoverflow posts and have tried the proposed solutions to no avail:
How to hide the onscreen keyboard when a DialogFragment is canceled by the setCanceledOnTouchOutside event
Close/hide the Android Soft Keyboard
The solution turned out to a combination of the following. To show the keyboard in a DialogFragment:
#Override
public void onResume()
{
super.onResume();
editText.post(new Runnable()
{
#Override
public void run()
{
editText.requestFocus();
InputMethodManager imm =
(InputMethodManager)editText.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
if (imm != null)
imm.showSoftInput(editText, InputMethodManager.SHOW_IMPLICIT);
}
});
}
To hide it, use the solution above by #Shekhar
#Override
public void onDismiss(DialogInterface dialog)
{
InputMethodManager imm =
(InputMethodManager)editText.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
if (imm.isActive())
imm.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS);
super.onDismiss(dialog);
}
Hiding keyboard in a View inside DialogFragment:
public static void hideKeyboardInAndroidFragment(View view){
final InputMethodManager imm = (InputMethodManager) view.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
}
For Hiding the Keyboard use this:
private void hideKeyboard() {
try {
InputMethodManager inputManager = (InputMethodManager) _activity
.getSystemService(Context.INPUT_METHOD_SERVICE);
inputManager.hideSoftInputFromWindow(_activity.getCurrentFocus()
.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
} catch (Exception e) {
}
}
for hide soft keyboard, you can use this method:
public void hideSoftKeyboard() {
try {
View windowToken = getDialog().getWindow().getDecorView().getRootView();
InputMethodManager imm = (InputMethodManager) getDialog().getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow( windowToken.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
} catch (Exception ex) {
Log.e(ex);
}
}
Hide it in DialogFragment onDestroyView() method:
View view = getActivity().getCurrentFocus();
if (view == null) view = new View(activity);
InputMethodManager imm = (InputMethodManager) getActivity().getSystemService(Activity.INPUT_METHOD_SERVICE);
if (imm == null) return;
imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
maybe work.
I had extension for fragment, but didn't work with dialog fragment. This extension works for both (not tested much tho)
/**
* If no window token is found, keyboard is checked using reflection to know if keyboard visibility toggle is needed
*
* #param useReflection - whether to use reflection in case of no window token or not
*/
fun Fragment.hideKeyboard(context: Context = App.instance, useReflection: Boolean = true) {
val windowToken = view?.rootView?.windowToken
val imm = context.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
windowToken?.let {
imm.hideSoftInputFromWindow(windowToken, 0)
} ?: run {
if (useReflection) {
try {
if (getKeyboardHeight(imm) > 0) {
imm.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS)
}
} catch (exception: Exception) {
Timber.e(exception)
}
}
}
}
fun getKeyboardHeight(imm: InputMethodManager): Int = InputMethodManager::class.java.getMethod("getInputMethodWindowVisibleHeight").invoke(imm) as Int
Edit: toggle opened keyboard if it was closed before, I use reflection to get keyboard's height, which is not best solution, but works
I found only one fully working approach if you want to show keyboard when dialog is shown and hide keyboard when dialog is dismissed
<style name="InputDialog" parent="ThemeOverlay.AppCompat.Dialog.Alert">
<item name="android:windowSoftInputMode">stateAlwaysVisible</item>
</style>
And then you should use the theme above inside your DialogFragment
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setStyle(STYLE_NORMAL, R.style.InputDialog)
}
Kotil Extension function for DialogFragment hide keyboard
use : hideKeyboard(view)
fun DialogFragment.hideKeyboard(view: View) {
val imm =view.context.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
imm.hideSoftInputFromWindow(view.windowToken, 0)
}

Android can't get token to change soft keyboard

I have a custom keyboard, where I have a button to change IME....
From the Android sample code, I've found the following:
InputMethodManager imeManager = (InputMethodManager) this.getSystemService(Context.INPUT_METHOD_SERVICE);
imeManager.switchToNextInputMethod(getToken(), false /* onlyCurrentIme */);
But I'm just getting can't resolve 'getToken()'... I'm doing this from a class that extends InputMethodService... What's the correct approach to getting the token from inside a keyboard then?
If not the above, then this one could work as well:
imeManager.showInputMethodPicker();
imeManager.hideSoftInputFromWindow(/*token?*/, 0);
My class:
public class CustomKeyboard extends InputMethodService implements KeyboardView.OnKeyboardActionListener {
private KeyboardView kv;
private Keyboard keyboard;
public final static int CodeRowFourGlobe = 55041;
#Override
public View onCreateInputView() {
kv = (KeyboardView)getLayoutInflater().inflate(R.layout.keyboard, null);
keyboard = new Keyboard(this, R.xml.custom_keyboard);
kv.setPreviewEnabled(false);
kv.setKeyboard(keyboard);
kv.setOnKeyboardActionListener(this);
return kv;
}
public void closeKeyboard(View view) {
InputMethodManager imeManager = (InputMethodManager) this.getSystemService(Context.INPUT_METHOD_SERVICE);
imeManager.switchToNextInputMethod(view.getWindowToken(), false /* onlyCurrentIme */);
}
#Override
public void onPress(int primaryCode) {
}
#Override
public void onRelease(int primaryCode) {
}
#Override
public void onKey(int primaryCode, int[] keyCodes) {
InputConnection ic = getCurrentInputConnection();
if (primaryCode == Keyboard.KEYCODE_DELETE) {
ic.deleteSurroundingText(1, 0);
} else if (primaryCode == CodeRowFourGlobe) {
InputMethodManager imeManager = (InputMethodManager) this.getSystemService(Context.INPUT_METHOD_SERVICE);
if (imeManager != null) {
Log.d(TAG, "Close keyboard");
} else {
Toast.makeText(this, R.string.no_keyboard_available, Toast.LENGTH_LONG).show();
}
} else {
}
}
}
I've tried:
InputMethodManager imm =(InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(kv.getApplicationWindowToken(), 0);
imm.switchToNextInputMethod(kv.getApplicationWindowToken(), false);
imm.switchToNextInputMethod(kv.getWindowToken(), false /* onlyCurrentIme */);
imm.hideSoftInputFromWindow(kv.getWindowToken(), 0);
So the trick for me was to use the following:
private IBinder getToken() {
final Dialog dialog = getWindow();
if (dialog == null) {
return null;
}
final Window window = dialog.getWindow();
if (window == null) {
return null;
}
return window.getAttributes().token;
}
This is working for me:
IBinder token = getWindow().getWindow().getAttributes().token;
Can be used anywhere inside an InputMethodService.
You could try something like this
public void fun(View view) {
InputMethodManager imeManager = (InputMethodManager) this.getSystemService(Context.INPUT_METHOD_SERVICE);
imeManager.switchToNextInputMethod(view.getWindowToken(), false /* onlyCurrentIme */);
}

Keyboard is not showing on single click

i am trying to show keyboard onclick
but it is not showing automatically (keyboard is in hidden state in manifest)
working but on double click...
here is the source.
search.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
search_friends.setVisibility(View.VISIBLE);
//my_friends.setVisibility(View.GONE);
search_friends.requestFocus();
if(search_friends.hasFocus())
{
getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE);
}
else
{
getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);
}
}
});
i want this on single click...
this is my method, I made it for an Util class, I use it in every project and it works:
/**
* For hide ed == null <br/>
* For show ed !=null
*
* #param context
* Activity
* #param ed
* EditText
*/
public static void hideOrShowSoftKeyboard(Activity context, EditText ed) {
try {
InputMethodManager inputManager = (InputMethodManager) context.getSystemService(context.INPUT_METHOD_SERVICE);
if (ed != null) {
inputManager.showSoftInput(ed, 0);
} else {
inputManager.hideSoftInputFromWindow(context.getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
}
} catch (NullPointerException e) {
LogService.log(TAG, "NullPointerException");
}
}
// in your implementation
#Override
public void onClick(View v) {
search_friends.setVisibility(View.VISIBLE);
//for showing the keyboard
AppNameUtils.hideOrShowSoftKeyboard(this,search_friends);
}

Open soft keyboard programmatically

I have an activity with no child widgets for it and the corresponding xml file is,
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/myLayout"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:focusable="true"
>
</LinearLayout>
and I want to open soft keyboard programmatically while the activity gets start.and what I've tried upto now is,
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
if (inputMethodManager != null) {
inputMethodManager.toggleSoftInput(InputMethodManager.SHOW_FORCED, 0);
}
Give me some guidance.
I have used the following lines to display the soft keyboard manually inside the onclick event, and the keyboard is visible.
InputMethodManager inputMethodManager =
(InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
inputMethodManager.toggleSoftInputFromWindow(
linearLayout.getApplicationWindowToken(),
InputMethodManager.SHOW_FORCED, 0);
But I'm still not able to open this while the activity gets opened, so are there any solution for this?
In your manifest file, try adding the following to the <activity> that you want to show the keyboard when the activity starts:
android:windowSoftInputMode="stateVisible"
This should cause the keyboard to become visible when the activity starts.
For more options, checkout the documentation.
Please follow the below code. I am sure your problem will be solved.
if (imm != null){
imm.toggleSoftInput(InputMethodManager.SHOW_FORCED,0);
}
This is works
<activity
...
android:windowSoftInputMode="stateVisible" >
</activity>
or
getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE);
All I needed was to expose the keyboard, in a very precise moment. This worked for me! Thanks Benites.
private Handler mHandler= new Handler();
And in the very precise moment:
mHandler.post(
new Runnable() {
public void run() {
InputMethodManager inputMethodManager = (InputMethodManager)getSystemService(INPUT_METHOD_SERVICE);
inputMethodManager.toggleSoftInputFromWindow(yourEditText.getApplicationWindowToken(), InputMethodManager.SHOW_FORCED, 0);
yourEditText.requestFocus();
}
});
I have used the following lines to display the soft keyboard manually inside the onclick event.
public void showKeyboard(final EmojiconEditText ettext){
ettext.requestFocus();
ettext.postDelayed(new Runnable(){
#Override public void run(){
InputMethodManager keyboard=(InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
keyboard.showSoftInput(ettext,0);
}
}
,200);
}
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);
}
Put that in onResume method:
findViewById(R.id.root_view_of_your_activity_layout).post(
new Runnable() {
public void run() {
InputMethodManager inputMethodManager = (InputMethodManager)getSystemService(INPUT_METHOD_SERVICE);
inputMethodManager.toggleSoftInputFromWindow(yourEditText.getApplicationWindowToken(), InputMethodManager.SHOW_FORCED, 0);
yourEditText.requestFocus();
}
});
the runnable is needed because when the OS fires the onResume method you can't be sure that all the views where draw, so the post method called from your root layout makes it wait till every view is ready.
in onCreate method of activity or onActivityCreated of a fragment
....
view.getViewTreeObserver().addOnPreDrawListener(new ViewTreeObserver.OnPreDrawListener() {
#Override
public boolean onPreDraw() {
view.removeOnPreDrawListener(this);
InputMethodManager imm = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
imm.toggleSoftInput(InputMethodManager.SHOW_FORCED, 0);
// !Pay attention to return `true`
// Chet Haase told to
return true;
}
});
seems like this is working
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_patientid);
editText = (EditText)findViewById(R.id.selectPatient);
//editText.requestFocus(); //works without that
}
#Override
protected void onResume() {
findViewById(R.id.selectPatient).postDelayed(
new Runnable() {
public void run() {
editText.requestFocus();
InputMethodManager inputMethodManager = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
inputMethodManager.showSoftInput(editText,InputMethodManager.SHOW_IMPLICIT);
}
},100);
super.onResume();
}
seems this works better:
in manifest:
<application>
<activity
android:name="com.doodkin.myapp.ReportActivity"
android:label="#string/title_activity_report"
android:screenOrientation="sensor"
android:windowSoftInputMode="stateHidden" > // add this or stateVisible
</activity>
</application>
seems the manifest working in android 4.2.2 but not working in android 4.0.3
I used it as singleton like:
public static void showSoftKeyboard(final Context context, final EditText editText) {
try {
editText.requestFocus();
editText.postDelayed(
new Runnable() {
#Override
public void run() {
InputMethodManager keyboard = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
keyboard.showSoftInput(editText, 0);
}
}
, 200);
} catch (NullPointerException npe) {
npe.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
Use it in your activity like:
showSoftKeyboard(this, yourEditTextToFocus);
I have used like this to show the soft keyboard programatically and this is worked for me to prevent the auto resize of the screen while launching the keyboard.
In manifest:
<activity android:name="XXXActivity" android:windowSoftInputMode="adjustPan">
</activity>
In XXXActvity:
EditText et = (EditText))findViewById(R.id.edit_text);
Timer timer = new Timer();
TimerTask task = new TimerTask() {
#Override
public void run() {
InputMethodManager inputMethodManager=(InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
inputMethodManager.toggleSoftInputFromWindow(et.getApplicationWindowToken(), InputMethodManager.SHOW_FORCED, 0);
}
};
timer.schedule(task, 200);
I assume this will save others time to search for this problem.
InputMethodManager inputMethodManager=(InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
inputMethodManager.toggleSoftInput(InputMethodManager.SHOW_FORCED,0);
This works:
private static void showKeyboard(Activity activity) {
View view = activity.getCurrentFocus();
InputMethodManager imm = (InputMethodManager) activity.getSystemService(Context.INPUT_METHOD_SERVICE);
imm.toggleSoftInput(InputMethodManager.SHOW_FORCED, 0);
}
And you call this method like this:
showKeyboard(NameOfActivity.this);
getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);
Use above code in onResume() to open soft Keyboard
InputMethodManager.SHOW_FORCED isn't good choice. If you use this setting you should manage hiding keyboard state. My suggestion is like this;
public void showSoftKeyboard(View view) {
InputMethodManager inputMethodManager = (InputMethodManager) getActivity().getSystemService(Activity.INPUT_METHOD_SERVICE);
view.requestFocus();
inputMethodManager.toggleSoftInput(InputMethodManager.SHOW_IMPLICIT, 0);
}
Also, you can focus on view (usually EditText) taking parameters it. This makes it a more useful function
for more info about InputMethodManager.SHOW_IMPLICIT and SHOW_FORCED; InputMethodManager
public final class AAUtilKeyboard {
public static void openKeyboard(final Activity activity, final EditText editText) {
final InputMethodManager imm = (InputMethodManager) activity.getSystemService(Context.INPUT_METHOD_SERVICE);
if (imm != null) {
imm.showSoftInput(editText, InputMethodManager.SHOW_IMPLICIT);
}
}
public static void hideKeyboard(final Activity activity) {
final View view = activity.getCurrentFocus();
if (view != null) {
final InputMethodManager imm = (InputMethodManager) activity.getSystemService(Context.INPUT_METHOD_SERVICE);
if (imm != null) {
imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
}
}
}
import androidx.core.view.WindowInsetsCompat.Type
import androidx.core.view.WindowInsetsControllerCompat
fun Activity.openKeyboard() {
WindowInsetsControllerCompat(window, window.decorView).show(Type.ime())
}
fun Activity.hideKeyboard() {
WindowInsetsControllerCompat(window, window.decorView).hide(Type.ime())
}
There are already too many answers but nothing worked for me apart from this
inputMethodManager.showSoftInput(emailET,InputMethodManager.SHOW_FORCED);
I used showSoftInput with SHOW_FORCED
And my activity has
android:windowSoftInputMode="stateVisible|adjustResize"
hope this helps someone
perfectly working code to show and hide softkeyboard for edittextbox.....
// code to hide soft keyboard
public void hideSoftKeyBoard(EditText editBox) {
InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(editBox.getWindowToken(), 0);
}
// code to show soft keyboard
private void showSoftKeyBoard(EditText editBox){
InputMethodManager inputMethodManager = (InputMethodManager) this.getSystemService(Activity.INPUT_METHOD_SERVICE);
editBox.requestFocus();
inputMethodManager.toggleSoftInput(InputMethodManager.SHOW_FORCED, 0);
}
Based on above answers like this it works in KOTLIN as long as you have the context.
fun Context.showKeyboard(editText: EditText) {
editText.requestFocus()
editText.setSelection(editText.text.length)
GlobalScope.launch {
delay(200L)
val inputMethodManager: InputMethodManager =
getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
inputMethodManager.toggleSoftInputFromWindow(
editText.applicationWindowToken,
InputMethodManager.SHOW_IMPLICIT, 0
)
}
}
Then you can call it in your fragment for example as follows
requireContext().showKeyboard(binding.myEditText)
Similar to the answer of #ShimonDoodkin this is what I did in a fragment.
https://stackoverflow.com/a/29229865/2413303
passwordInput.postDelayed(new ShowKeyboard(), 300); //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.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);
This is the required source code :
public static void openKeypad(final Context context, final View v)
{
new Handler().postDelayed(new Runnable()
{
#Override
public void run()
{
InputMethodManager inputManager = (InputMethodManager)context.getSystemService(Context.INPUT_METHOD_SERVICE);
inputManager.showSoftInput(v, InputMethodManager.SHOW_IMPLICIT);
Log.e("openKeypad", "Inside Handler");
}
},300);}
For details , Please go through this link. This helped me.
https://github.com/Nikhillosalka/Keyboard/blob/master/README.md
Post this method in your base activity and use it other activities like a charm
public void openKeyboard() {
InputMethodManager imm =
(InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
if (imm != null) {
imm.toggleSoftInput(InputMethodManager.SHOW_FORCED, 0);
}
}
I like to do it as an extension to Context so you can call it anywhere
fun Context.showKeyboard(editText: EditText) {
val inputMethodManager: InputMethodManager =
getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
inputMethodManager.toggleSoftInputFromWindow(
editText.applicationWindowToken,
InputMethodManager.SHOW_IMPLICIT, 0
)
editText.requestFocus()
editText.setSelection(editText.text.length)
}
fun Context.hideKeyboard(editText: EditText) {
val imm = getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
imm.hideSoftInputFromWindow(editText.windowToken, 0)
}
In the Kotlin, you can use the below extension functions to show and hide the soft keyboard.
/**
* Extension method to provide show keyboard for [Activity].
*/
fun Activity.showSoftKeyboard() {
if (currentFocus != null) {
val inputMethodManager =
getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
inputMethodManager.showSoftInput(this.currentFocus,InputMethodManager.SHOW_IMPLICIT)
}
}
/**
* Extension method to provide hide keyboard for [Activity].
*/
fun Activity.hideSoftKeyboard() {
if (currentFocus != null) {
val inputMethodManager =
getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
inputMethodManager.hideSoftInputFromWindow(currentFocus!!.windowToken, 0)
}
}
That's all!
Cheers!
If you want the keyboard to be up along with the activity/fragment launch, you can use the below code.
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
InputMethodManager inputMethodManager =
(InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
inputMethodManager.toggleSoftInputFromWindow(
etPhoneNumber.getApplicationWindowToken(),
InputMethodManager.SHOW_FORCED, 0);
}
}, 500);
Best way to open Keyboard is to call the below kotlin code:
val inputMethodManager: InputMethodManager =
getSystemService(INPUT_METHOD_SERVICE) as InputMethodManager
inputMethodManager.showSoftInput(editText, 2)
Try use this:
fun closeKeyboard(view: View) {
(getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager)
.hideSoftInputFromWindow(view.windowToken, HIDE_IMPLICIT_ONLY)
}
fun showKeyBoard(view: View) {
(getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager).showSoftInput(
view,
SHOW_IMPLICIT
)
}
And if not work, try wrap func in a run block like this:
view.postDelayed({showKeyBoard(view)},100)

how to hide keyboard after typing in EditText in android?

I have a EditText and button aligned to parent's bottom.
When I enter text in it and press the button to save data, the virtual keyboard does not disappear.
Can any one guide me how to hide the keyboard?
You might also want to define the imeOptions within the EditText. This way, the keyboard will go away once you press on Done:
<EditText
android:id="#+id/editText1"
android:inputType="text"
android:imeOptions="actionDone"/>
This should work.
InputMethodManager inputManager = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
inputManager.hideSoftInputFromWindow(this.getCurrentFocus().getWindowToken(),InputMethodManager.HIDE_NOT_ALWAYS);
Just make sure that this.getCurrentFocus() does not return null, which it would if nothing has focus.
mEtNumber.setOnEditorActionListener(new TextView.OnEditorActionListener() {
#Override
public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
if (actionId == EditorInfo.IME_ACTION_DONE) {
// do something, e.g. set your TextView here via .setText()
InputMethodManager imm = (InputMethodManager) v.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
return true;
}
return false;
}
});
and in xml
android:imeOptions="actionDone"
getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
I did not see anyone using this method:
editText.setOnFocusChangeListener(new View.OnFocusChangeListener() {
#Override
public void onFocusChange(View view, boolean focused) {
InputMethodManager keyboard = (InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
if (focused)
keyboard.showSoftInput(editText, 0);
else
keyboard.hideSoftInputFromWindow(editText.getWindowToken(), 0);
}
});
And then just request focus to the editText:
editText.requestFocus();
Solution included in the EditText action listenner:
public void onCreate(Bundle savedInstanceState) {
...
...
edittext = (EditText) findViewById(R.id.EditText01);
edittext.setOnEditorActionListener(new OnEditorActionListener() {
public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
if (event != null&& (event.getKeyCode() == KeyEvent.KEYCODE_ENTER)) {
InputMethodManager in = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
in.hideSoftInputFromWindow(edittext.getApplicationWindowToken(),InputMethodManager.HIDE_NOT_ALWAYS);
}
return false;
}
});
...
...
}
I found this because my EditText wasn't automatically getting dismissed on enter.
This was my original code.
editText.setOnEditorActionListener(new TextView.OnEditorActionListener() {
#Override
public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
if ( (actionId == EditorInfo.IME_ACTION_DONE) || ((event.getKeyCode() == KeyEvent.KEYCODE_ENTER) && (event.getAction() == KeyEvent.ACTION_DOWN ))) {
// Do stuff when user presses enter
return true;
}
return false;
}
});
I solved it by removing the line
return true;
after doing stuff when user presses enter.
Hope this helps someone.
Just write down these two lines of code where enter option will work.
InputMethodManager inputManager = (InputMethodManager) getSystemService(Activity.INPUT_METHOD_SERVICE);
inputManager.hideSoftInputFromWindow(view.getWindowToken(), 0);
Been struggling with this for the past days and found a solution that works really well. The soft keyboard is hidden when a touch is done anywhere outside the EditText.
Code posted here: hide default keyboard on click in android
you can create a singleton class for call easily like this:
public class KeyboardUtils {
private static KeyboardUtils instance;
private InputMethodManager inputMethodManager;
private KeyboardUtils() {
}
public static KeyboardUtils getInstance() {
if (instance == null)
instance = new KeyboardUtils();
return instance;
}
private InputMethodManager getInputMethodManager() {
if (inputMethodManager == null)
inputMethodManager = (InputMethodManager) Application.getInstance().getSystemService(Activity.INPUT_METHOD_SERVICE);
return inputMethodManager;
}
#SuppressWarnings("ConstantConditions")
public void hide(final Activity activity) {
new Handler().post(new Runnable() {
#Override
public void run() {
try {
getInputMethodManager().hideSoftInputFromWindow(activity.getCurrentFocus().getWindowToken(), 0);
} catch (NullPointerException e) {
e.printStackTrace();
}
}
});
}
}
so, after can call in the activity how the next form:
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity);
KeyboardUtils.getInstance().hide(this);
}
}
You can see marked answer on top. But i used getDialog().getCurrentFocus() and working well. I post this answer cause i cant type "this" in my oncreatedialog.
So this is my answer. If you tried marked answer and not worked , you can simply try this:
InputMethodManager inputManager = (InputMethodManager) getActivity().getApplicationContext().getSystemService(Context.INPUT_METHOD_SERVICE);
inputManager.hideSoftInputFromWindow(getDialog().getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
I use this method to remove keyboard from edit text:
public static void hideKeyboard(Activity activity, IBinder binder) {
if (activity != null) {
InputMethodManager inputManager = (InputMethodManager) activity.getSystemService(Context.INPUT_METHOD_SERVICE);
if (binder != null && inputManager != null) {
inputManager.hideSoftInputFromWindow(binder, 0);//HIDE_NOT_ALWAYS
inputManager.showSoftInputFromInputMethod(binder, 0);
}
}
}
And this method to remove keyboard from activity (not work in some cases - for example, when edittext, to wich is binded keyboard, lost focus, it won't work. But for other situations, it works great, and you do not have to care about element that holds the keyboard).
public static void hideKeyboard(Activity activity) {
if (activity != null) {
InputMethodManager inputManager = (InputMethodManager) activity.getSystemService(Context.INPUT_METHOD_SERVICE);
if (activity.getCurrentFocus() != null && inputManager != null) {
inputManager.hideSoftInputFromWindow(activity.getCurrentFocus().getWindowToken(), 0);
inputManager.showSoftInputFromInputMethod(activity.getCurrentFocus().getWindowToken(), 0);
}
}
}
int klavStat = 1; // for keyboard soft/hide button
int inType; // to remeber your default keybort Type
editor - is EditText field
/// metod for onclick button ///
public void keyboard(View view) {
if (klavStat == 1) {
klavStat = 0;
inType = editor.getInputType();
InputMethodManager imm = (InputMethodManager)
getSystemService(Context.INPUT_METHOD_SERVICE);
imm.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS);
editor.setInputType(InputType.TYPE_NULL);
editor.setTextIsSelectable(true);
} else {
klavStat = 1;
InputMethodManager imm = (InputMethodManager)
getSystemService(Context.INPUT_METHOD_SERVICE);
imm.toggleSoftInput(InputMethodManager.SHOW_IMPLICIT, 0);
editor.setInputType(inType);
}
}
If you have another EditText Field, you need to watch for focus change.
In my case, in order to hide the keyboard when pressing the "send button", I used the accepted answer but changed context to getApplication and added getWindow().
InputMethodManager inputManager = (InputMethodManager) getApplication().getSystemService(Context.INPUT_METHOD_SERVICE);
inputManager.hideSoftInputFromWindow(getWindow().getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
editText.setInputType(InputType.TYPE_NULL);

Categories

Resources