Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android dispatchKeyEvent not called when Dialog fragment is show

when my dialog fragment is hide, dispatchKeyEvent worked fine

@Override
public boolean dispatchKeyEvent(KeyEvent event) {

    Toast.makeText(FragmentPlayer.this, "test: called", Toast.LENGTH_SHORT).show();

    return super.dispatchKeyEvent(event);

}

but when my dialog fragment is show, dispatchKeyEvent not called

MyDialogFragment mFragment = new MyDialogFragment();
mFragment.show(getSupportFragmentManager(), "MyDialog");

why?

like image 385
Farzad Avatar asked Feb 20 '17 20:02

Farzad


1 Answers

No need to change your DialogFragment code to Dialog, you can do something like this (In case still needed). Using OnKeyListener will solve your problem.

public class BaseDialogFragment extends AppCompatDialogFragment {

  @Override
  public void onActivityCreated(Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);
    getDialog().setOnKeyListener(new DialogInterface.OnKeyListener() {
        @Override
        public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {
            /* Your logic, you get the KeyEvent*/
            return false;
        }
    });
}
like image 99
Siddharth jain Avatar answered Nov 10 '22 15:11

Siddharth jain