Farzad
Farzad

Reputation: 2090

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?

Upvotes: 5

Views: 5709

Answers (2)

Siddharth jain
Siddharth jain

Reputation: 447

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;
        }
    });
}

Upvotes: 9

Zahra.HY
Zahra.HY

Reputation: 1692

Inside your DialogFragment for your keys` actions, you can use:

getDialog().dispatchKeyEvent(event);

instead of

getActivity().dispatchKeyEvent(event);

Upvotes: 0

Related Questions