-1
private void hideKeyboard() {
    try {
        // Close Soft Keyboard
        InputMethodManager inputManager = (InputMethodManager)
                mContext.getSystemService(Context.INPUT_METHOD_SERVICE);

        inputManager.hideSoftInputFromWindow(rootView.getWindowToken(),
                InputMethodManager.HIDE_NOT_ALWAYS);
    } catch (Exception keyboardHideExp) {
        Log.d("eEmp/HideKbExp", "Exception raised due to " + keyboardHideExp.toString());
    }
}

This was used in fragment. I need to use same method in my class but giving error at rootView. How can I access in my class.

inputManager.hideSoftInputFromWindow(rootView.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);

I am new to android.

Any help would be appreciated.

thepoosh
  • 12,193
  • 14
  • 68
  • 129
kalyan
  • 17
  • 5

3 Answers3

1

Try this code.

Context mcontext;
View rootView;
classConstructor(Context context, View view){
this.mcontext = context;
this.rootView = view;
}
private void hideKeyboard()
{
try {
// Close Soft Keyboard
InputMethodManager inputManager = (InputMethodManager)
                mContext.getSystemService(Context.INPUT_METHOD_SERVICE);

inputManager.hideSoftInputFromWindow(rootView.getWindowToken(),
                InputMethodManager.HIDE_NOT_ALWAYS);
} catch (Exception keyboardHideExp) {
        Log.d("eEmp/HideKbExp", "Exception raised due to " + keyboardHideExp.toString());
}
}
singh.indolia
  • 1,177
  • 12
  • 24
0

You need parent View. How your method is getting rootView variable?
The simplest way is:

In YourClass.class

public void closeKeyboard(Context context, View view) {
   InputMethodManager inputMethodManager =(InputMethodManager)context.getSystemService(Activity.INPUT_METHOD_SERVICE);
   inputMethodManager.hideSoftInputFromWindow(view.getWindowToken(), 0);
}  

Or instead of view.getWindowToken() use context.getCurrentFocus().getWindowToken().

In YourActivity.class

EditText editText = findViewById(R.id.my_edit_text);
new YourClass().closeKeyboard(this, editText);  

The EditText should be in activity/fragment layout.

Dumbo
  • 1,424
  • 13
  • 29
0

You can use this as you using Fragment.

private void hideKeyBoard() {
    if (getActivity().getCurrentFocus() != null) {
        InputMethodManager imm = (InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.hideSoftInputFromWindow(getActivity().getCurrentFocus().getWindowToken(), 0);
    }
}

It's works for me...