Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to ignore 'search' key press in DialogFragment

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.

like image 565
Adil Hussain Avatar asked Aug 08 '12 18:08

Adil Hussain


1 Answers

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
  }
});
like image 121
nandeesh Avatar answered Sep 18 '22 21:09

nandeesh