Android dispatchKeyEvent not called when Dialog fragment is show
Asked Answered
N

2

5

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?

Notification answered 20/2, 2017 at 20:49 Comment(4)
I have the same problem, Did you figure that out?Barthol
@Barthol i found issue and fixed itNotification
@grizzly What is the issue? I have similar problem.Cabalistic
@Yeung. you must use ... extends Dialog. not use dialog fragment. Simple Dialog class dispatchKeyEvent fix and is ok. when dialog fragment is show, dispatchKeyEvent not working. so you should use Dialog classNotification
I
9

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;
        }
    });
}
Inspirit answered 26/10, 2017 at 10:10 Comment(2)
hi, How to add setOnKeyListener in a fragment. I am trying to read an RFID HID device from a fragment. Tried adding a listener in the root view but not workingJaeger
@AravindOR You will need to listen key event on the fragment's activity. override dispatchKeyEvent() and check if the current fragment is the required oneInspirit
M
0

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

getDialog().dispatchKeyEvent(event);

instead of

getActivity().dispatchKeyEvent(event);
Mithridatism answered 17/2, 2019 at 13:19 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.