How to ignore 'search' key press in DialogFragment

android, android-dialog, android-dialogfragment, android-fragments, android-keypad

Solution

Try this. Inside your `DialogFragment.Onresume`

 getDialog().setOnKeyListener(new OnKeyListener()
 {
    public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event){
    if (keyCode == KeyEvent.KEYCODE_SEARCH)
      return true; // pretend we've processed it
    else
      return false; // pass on to be processed as normal
  }
});

Problem

I was previously extending the `Dialog` class for my dialogs and I had to use the following code segment in my dialogs so that they would not be dismissed when the phone's search key was pressed: ``` setOnKeyListener(new OnKeyListener() { public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) { if (keyCode == KeyEvent.KEYCODE_SEARCH) return true; // pretend we've processed it else return false; // pass on to be processed as normal } }); ``` I am now using the `DialogFragment` class for my dialogs. Unfortunately `DialogFragment` has the same problem as `Dialog` in that dialogs are dismissed when the phone's search key is pressed (regardless of the dialog's cancelable state). Doubly problematic is that `DialogFragment` does not have a `setOnKeyListener` method so the above code segment no longer applies. Anyone know how I can get my dialogs (when showing) to ignore search key presses? Note: I tried adding the above code segment to my activity's `onKeyUp` method but unfortunately my activity's `onKeyUp` method is not called if a `DialogFragment` instance is showing. Instead, irritatingly, the `DialogFragment` instance is dismissed.

Original source