'Android TextInputEditText default context menu, dismiss programmatically

I would like to as if there is a way to programmatically dismiss the context menu of android .

The menu shows whenever I long press the TextInputEditText. "Cut", "Copy", "Paste", "Share".

I want to dismiss this menu when either pressing a button or just pressing outside the TextInputEditText.

Currently, nothing happens when I do the above actions. It only gets dismissed whenever I choose an option or press the back button.

Sample Image



Solution 1:[1]

For the mean time I used "clearFocus()" to dismiss the active context menu.

I added this after dismissing the keyboard to ensure that it will not interfere with the process of closing the keyboard on the current active textField.

fun hideSoftKeyboard(activity: Activity) {
    val inputMethodManager: InputMethodManager = activity.getSystemService(Activity.INPUT_METHOD_SERVICE) as InputMethodManager
       if (inputMethodManager.isAcceptingText) {
           //Close keyboard
           inputMethodManager.hideSoftInputFromWindow(
             activity.currentFocus?.windowToken,
             0
           )

           //Remove focus and open context menu from the current selected TextField
           activity.currentFocus?.clearFocus()
       }
}

Usage:

From Fragment:

hideSoftKeyboard((activity as AppCompatActivity))

From Activity:

hideSoftKeyboard(this@MainActivity)

or

hideSoftKeyboard(this)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Neil