hide Keyboard in fragment android java code example

Example 1: android hide keyboard

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

// call from inside an Activity...
hideKeyboard(this, view);
hideKeyboard(this, getCurrentFocus());
hideKeyboard(this, getWindow().getDecorView());
hideKeyboard(this, findViewById(android.R.id.content));

Example 2: hide keyboard android kotlin

class CloseHideSoftKeyboard : AppCompatActivity() {
  
 override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_message)

        val editTextXml = findViewById<EditText>(R.id.editText)
        val btnSendMessage = findViewById<Button>(R.id.btnSend)
        
        btnSendMessage.setOnClickListener{
          // ... you actions
          // Important! EditText must have be focused 
          // do action close keyboard first before go to another
          // activity or fragment
        	closeSoftKeyboard(this, editTextXml)
        }
    }



   /* hide soft keyboard after writing and sending message or any */
   private fun closeSoftKeyboard(context: Context, v: View) {
        val iMm = context.getSystemService(Activity.INPUT_METHOD_SERVICE) as InputMethodManager
        iMm.hideSoftInputFromWindow(v.windowToken, 0)
        v.clearFocus()
    }
}
// link to resourse (Russian version)
// https://issue.life/questions/1109022/close-hide-the-android-soft-keyboard

Tags:

Java Example