android hide soft keyboard 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: android how to don't show keyboard

getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);

Example 3: android dismiss keyboard

InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(myEditText.getWindowToken(), 0);

Example 4: how to open soft keyboard in android programmatically

class MainActivity: AppCompatActivity() {

	override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_message)
		val editTextMessage = findViewById<EditText>(R.id.myEditeText)
      	showSoftKeyboard(this, editTextMessage)
    }


  	private fun showSoftKeyboard(context: Context, v: View) {
    	val iim = context.getSystemService(Activity.INPUT_METHOD_SERVICE) as InputMethodManager
    	if (v.requestFocus()) {
      		iim.showSoftInput(v, InputMethodManager.SHOW_IMPLICIT)
    	}
  	}
}

Tags:

Java Example