显示Dialog片段时未调用Android dispatchKeyEvent

时间:2017-02-20 20:49:50

标签: android android-fragments android-dialogfragment

当我的对话框片段为hide时,dispatchKeyEvent工作正常

@Override
public boolean dispatchKeyEvent(KeyEvent event) {

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

    return super.dispatchKeyEvent(event);

}

但是当我的对话框片段为show时,dispatchKeyEvent未被调用

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

为什么?

2 个答案:

答案 0 :(得分:2)

无需将DialogFragment代码更改为Dialog,您可以执行以下操作(如果仍需要)。使用OnKeyListener可以解决您的问题。

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

答案 1 :(得分:0)

DialogFragment 中执行按键操作时,可以使用:

getDialog().dispatchKeyEvent(event);

代替

getActivity().dispatchKeyEvent(event);