Hide Keyboard when Button Click (Fragment) - android

i got error to implement hide keyboard when button click, anyone know how to fix that?
actually code error in getSystemService and getWindowsToken
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_calculator, container, false);
Button hitung = (Button) rootView.findViewById(R.id.hitung);
final EditText height = (EditText)rootView.findViewById(R.id.height);
final EditText weight = (EditText)rootView.findViewById(R.id.weight);
InputMethodManager imm = InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(EditText.getWindowToken(), 0);
final TextView result = (TextView)rootView.findViewById(R.id.result);
final TextView finalresult = (TextView)rootView.findViewById(R.id.finalresult);
finalresult.setMovementMethod(new ScrollingMovementMethod());
hitung.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
..........
}

you are using Fragment so write like getActivity().getSystemService(Context.INPUT_METHOD_SERVICE)
Reason for the same :
An Activity extends Context, a Fragment does not. Hence, you first need to get a reference to the Activity in which the Fragment is contained
Edit
for the other error you mentioned in the comment you can use
getView().getWindowToken()
and the hide method should be called inside your button's onClick() method like
imm.hideSoftInputFromWindow(getView().getWindowToken(), 0);

use this,
public static void hideKeyboard(Context mContext) {
InputMethodManager imm = (InputMethodManager) mContext
.getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(((Activity) mContext).getWindow()
.getCurrentFocus().getWindowToken(), 0);
}

use below code
try {
InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
inputMethodManager.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(),
InputMethodManager.HIDE_NOT_ALWAYS);
} catch (Exception e) {
if(net.one97.paytm.common.utility.CJRAppCommonUtility.isDebug) e.printStackTrace();
}

// hide keyboard
public static void hideSoftKeyboard(Context context, View view) {
InputMethodManager inputMethodManager = (InputMethodManager) context.getSystemService(Activity.INPUT_METHOD_SERVICE);
if(inputMethodManager != null && inputMethodManager.isActive())
{
//inputMethodManager.hideSoftInputFromWindow(activity.getCurrentFocus().getWindowToken(), 0);
//InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
inputMethodManager.hideSoftInputFromWindow(view.getWindowToken(), 0);
}
}

hitung.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v)
{
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), 0);
}
});

well in Koltin you can do it like..
fun View.hideKeyboard() {
val imm = getSystemService(context,
InputMethodManager::class.java) as InputMethodManager
imm.hideSoftInputFromWindow(windowToken, 0)
}
call this extension function form any view any time when you want to hide keyboard when it is clicked !

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

Cannot hide Android soft keyboard even with inputmanager

Problem:
I want to hide the keyboard when the button "Add" is pressed. There are two EditText on the screen. The keyboard doesn't appear at starting the activity, which is good, but it doesn't go away on clicking button.
Here are all the possible questions from Stack Overflow that I have seen whose answers don't help me:
Close/hide the Android Soft Keyboard
Programmatically Hide/Show Android Soft Keyboard
How to hide Soft Keyboard when activity starts
How to hide soft keyboard on android after clicking outside EditText?
and many others.
Here is my code:
AddActivity
public class AddActivity extends ActionBarActivity {
EditText text1,text2;
DbHelper db;
ListView l;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add);
db = new DbHelper(this);
l = (ListView) findViewById(R.id.listInAddActivity);
text1 = (EditText) findViewById(R.id.i1);
text2 = (EditText) findViewById(R.id.i2);
// text1.setInputType(InputType.TYPE_NULL);
// text2.setInputType(InputType.TYPE_NULL);
hideKeyboard();
loadDataInAdd();
}
public void addNewTask(View view) {
String s1 = text1.getText().toString();
String s2 = text2.getText().toString();
db.addData(s1,s2);
loadDataInAdd();
hideKeyboard();
}
public void loadDataInAdd()
{
try {
Cursor cursor = db.fetchData();
ListAdapter myAdapter = new SimpleCursorAdapter(this, R.layout.tasks,
cursor,
new String[]{db._ID, db.COLUMN_1, db.COLUMN_2},
new int[]{R.id.idnum, R.id.c1, R.id.c2}, 0);
l.setAdapter(myAdapter);
}
catch(NullPointerException e)
{
e.printStackTrace();
}
// MainActivity.loadData();
}
private void hideKeyboard() {
// Check if no view has focus:
View view = this.getCurrentFocus();
if (view != null) {
InputMethodManager inputManager = (InputMethodManager) this.getSystemService(Context.INPUT_METHOD_SERVICE);
inputManager.hideSoftInputFromWindow(view.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
}
}
}
Most answers are about the InputManager method, but it does not work for me, i.e., does not hide the keyboard when clicking on the button. Here is another variation of InputManager I used:
View view = this.getCurrentFocus();
if (view != null) {
InputMethodManager inputManager = (InputMethodManager) this.getSystemService(Context.INPUT_METHOD_SERVICE);
inputManager.hideSoftInputFromWindow(view.getWindowToken(), 0);
I also tried this:
getWindow().setSoftInputMode(
WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN
);
and this does not work either (keyboard isn't hidden on clicking button).
I have also tried:
<activity android:name=".AddActivity"
android:label="#string/app_name"
android:parentActivityName=".MainActivity"
android:windowSoftInputMode="stateAlwaysHidden">
</activity>
and
<activity android:name=".AddActivity"
android:label="#string/app_name"
android:parentActivityName=".MainActivity"
android:windowSoftInputMode="stateAlwaysHidden">
</activity>
With this one, my app stopped working:
InputMethodManager inputManager = (InputMethodManager)
getSystemService(Context.INPUT_METHOD_SERVICE);
inputManager.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(),
InputMethodManager.HIDE_NOT_ALWAYS);
This one totally hid the keyboard (the keyboard did not appear even when the editText was clicked):
text1.setInputType(InputType.TYPE_NULL);
text2.setInputType(InputType.TYPE_NULL);
I decided to use an onclicklistener for my button, instead of using another function and calling it via onClick in AddActivity.xml.
I was halfway through my question when I decided to try using OnCliCkListener once again. After several random tries, the following is the final code that works for me:
btn.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
InputMethodManager inputManager = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);
inputManager.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), 0);
}
});
Another way is to use OnClickListener in the following manner:
private View.OnClickListener mListener = new View.OnClickListener() {
public void onClick(View v) {
// do something when the button is clicked
//public void onClick(View v) {
try {
InputMethodManager inputManager = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);
inputManager.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), 0);
}
catch (Exception e) {
e.printStackTrace();
}
}
};
Important points for beginners like me:
The above code should be placed before protected void onCreate(Bundle savedInstanceState)
To call the above, place this code in protected void onCreate(Bundle savedInstanceState):
btn.setOnClickListener(mListener);
Use try-catch for exception handling in both methods (onClickListener, setOnClickListener)
Upon searching for why onClick, the XML attribute doesn't work for me, while OnClickListener does, I have found the following links useful:
setOnclickListener vs OnClickListener vs View.OnClickListener
Android onClick in XML vs. OnClickListener
How exactly does the android:onClick XML attribute differ from setOnClickListener?
Difference between OnClick() event and OnClickListener?
Now, halfway through my answer, I realized my mistake in using the onClick from XML. Here is what I did to get rid of the OnClickListeners:
First, I moved the part of my code which hid the keyboard into the method in onClick. Here in my case, I moved the entire code inside hideKeyboard() to addNewTask.
Some important points regarding using onClick
The method should be public and void.
It should take a View parameter, such as View V.
Finally, the code that works:
public void addNewTask(View view) {
String s1 = text1.getText().toString();
String s2 = text2.getText().toString();
db.addData(s1, s2);
loadDataInAdd();
// hideKeyboard(); below is the code to hide keyboard
if (view != null) {
InputMethodManager inputManager = (InputMethodManager) this.getSystemService(Context.INPUT_METHOD_SERVICE);
inputManager.hideSoftInputFromWindow(view.getWindowToken(), 0);
}
}
Summary
I found 3 ways to hide soft keyboard for my case, using:
OnClickListener :
private View.OnClickListener mListener = new View.OnClickListener() {
public void onClick(View v) {
// do something when the button is clicked
//public void onClick(View v) {
try {
InputMethodManager inputManager = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);
inputManager.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), 0);
}
catch (Exception e) {
e.printStackTrace();
}
}
};
setOnClickListener:
btn.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
InputMethodManager inputManager = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);
inputManager.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), 0);
}
});
onClick, the XML attribute:
public void addNewTask(View view) {
String s1 = text1.getText().toString();
String s2 = text2.getText().toString();
db.addData(s1, s2);
loadDataInAdd();
// hideKeyboard();
if (view != null) {
InputMethodManager inputManager = (InputMethodManager) this.getSystemService(Context.INPUT_METHOD_SERVICE);
inputManager.hideSoftInputFromWindow(view.getWindowToken(), 0);
}
}
this will help you to hide your keyboard on startup until you touch the edit text.
getWindow().setSoftInputMode(
WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN
);
in your case, try this
btn.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
}
});
Check this out
View view = this.getCurrentFocus();
if (view != null) {
InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
}
Close/hide the Android Soft Keyboard

Close/hide the Android Soft Keyboard on activity state onStop

I have an EditText and a Button in my layout. After writing in the edit field and click this button to go back my fragment, I want to hide the virtual keyboard. I assume that there's a simple, but i tried some way and it not work:
That code show how the Button work:
private void onButtonClicked(){
getActivity().getSupportFragmentManager().popBackStack();
}
That code for some solution but that can't help.
This code i using hideSoftInputFromWindow but when i call 'EditText.getWindowToken()', it not hide the soft keyboard (I also change the 0 value to InputMethodManager.HIDE_IMPLICIT_ONLY or InputMethodManager.HIDE_NOT_ALWAYS and it not work):
EditText myEditText = (EditText) findViewById(R.id.myEditText);
InputMethodManager imm = (InputMethodManager)getSystemService(
Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(myEditText.getWindowToken(), 0);
With this code, in another screen of this app, it work. This screen is an activity so i think that problem is fragment's problem.
My fragment code:
public class ChangeEmailFragment extends BaseFragment {
private TextView mTxtCurrentEmail;
private EditText mEdtNewEmail;
private EditText mEdtPassword;
private TextView mTxtSubmit;
#Override
public void onStop() {
super.onStop();
if (progressDialog != null && progressDialog.isShowing())
progressDialog.dismiss();
if (dialog != null && dialog.isShowing())
dialog.dismiss();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_change_email, container,
false);
mTxtCurrentEmail = (TextView) view.findViewById(R.id.current_email);
mEdtNewEmail = (EditText) view.findViewById(R.id.edit_email);
mEdtPassword = (EditText) view.findViewById(R.id.edit_password);
mTxtSubmit = (TextView) view.findViewById(R.id.button_submmit);
return view;
}
private void showErrorDialog(String msg) {
Builder builder = new Builder(getActivity());
builder.setTitle(getString(R.string.fg_change_email_dialog_error_title));
builder.setMessage(msg);
builder.setNegativeButton(getText(R.string.common_ok), null);
dialog = builder.create();
dialog.show();
}
}
My activity code:
#Override
public void onStop() {
super.onStop();
InputMethodManager imm = (InputMethodManager) getSystemService(
Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(mEdtUserName.getWindowToken(), 0);
}
Try this way in Fragment
InputMethodManager imm = (InputMethodManager)getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(getView().getWindowToken(), 0);

Hide soft keyboard after dialog dismiss

I want to hide soft keyboard after AlertDialog dismiss, but it's still visible. Here is my code:
alert = new AlertDialog.Builder(MyActivity.this);
imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
alert.setOnDismissListener(new DialogInterface.OnDismissListener() {
#Override
public void onDismiss(DialogInterface dialog) {
imm.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), 0);
}
});
In Manifest xml
android:windowSoftInputMode="stateAlwaysHidden"
It will automatically hide soft keyboard on Dismiss of Dialog
I met the same problem. Solved it by doing like this. It doesn't need any reference:
imm.hideSoftInputFromWindow(getWindow().getDecorView()
.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
I had a similar problem when closing an alert dialog. This seems to do the trick for me.
Inside your DialogFragment
public static void closeKB(final View view)
{
caller.postDelayed(new Runnable() {
#Override
public void run() {
InputMethodManager imm = (InputMethodManager) view.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(view.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
}
}, 1);
}
#Override
public void onDismiss(DialogInterface dialog)
{
super.onDismiss(dialog);
View view = getActivity().getCurrentFocus();
if (view != null)
{
closeKB(view);
}
}
I use this method:
IBinder token = searchTextEntry.getWindowToken();
( ( InputMethodManager ) getSystemService( Context.INPUT_METHOD_SERVICE ) ).hideSoftInputFromWindow( token, 0 );
Where searchTextEntry is the name of my EditText reference.
This works! This will close the keyboard after dialog dismiss
InputMethodManager imm = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
imm.toggleSoftInput(InputMethodManager.HIDE_IMPLICIT_ONLY, 0);
protected void hideKeyboard() {
final Activity activity = getActivity();
final View view = activity != null ? activity.getCurrentFocus() : null;
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
if (view != null) {
InputMethodManager imm = (InputMethodManager) activity.getSystemService(Context.INPUT_METHOD_SERVICE);
if (imm != null)
imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
}
}
}, 1);
}
#Override
public void onDismiss(DialogInterface dialog) {
super.onDismiss(dialog);
hideKeyboard();
}
All these advices to use InputMethodManager are somewhat vague - where exactly to call it, and they do not work at least for me.
Yes, keyboard disappears but then the app crashes!?
The main problem is that hiding of keyboard happens at the same time when dialog is disappearing.
To avoid it dialog.dismiss() should be called in view.postDelayed() after imm.hideSoftInputFromWindow() and in my case I set delay as 150.
in case anyone looks for this in kotlin, it would be:
private fun hideDeviceKeyboard() {
val imm = context!!.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
imm.toggleSoftInput(InputMethodManager.HIDE_IMPLICIT_ONLY, 0)
}

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)

Categories

Resources