当DiaglogFragment打开时,如何捕获后退按钮?

时间:2015-07-17 17:26:56

标签: android back-button android-dialogfragment

用户可以点击DialogFragment'取消"按钮或"确定"屏幕上或设备上的后退按钮上的按钮。取消和确定按钮的代码工作正常。单击后退按钮时,目标是关闭(关闭)DialogFragement并返回上一个活动。我的后退按钮代码不起作用,请指教。

public class CreateSkycardFragment extends DialogFragment {

public CreateSkycardFragment() {
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    View rootView = inflater.inflate(R.layout.skyfrag_layout, container, false);
    getDialog().setTitle("Delete skycard");


    // if the user clicks "Cancel" in the "Delete skycard" dialog.
    Button btnCancel = (Button) rootView.findViewById(R.id.btnCancel);
    btnCancel.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            InputMethodManager imm = (InputMethodManager) getActivity().getSystemService(CardViewActivity.INPUT_METHOD_SERVICE);
            imm.toggleSoftInput(InputMethodManager.SHOW_IMPLICIT, 0);
            getDialog().cancel();
        }
    });

    // if the user clicks "OK" in the "Delete skycard" dialog.
    Button btnOK = (Button) rootView.findViewById(R.id.btnOK);
    btnOK.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            dismiss();
            getActivity().finish();
        }
    });

    // if the user presses the Back Button even with the "Delete skycard" dialog open.
    // the below code is where I'm having trouble
    .setOnBackPressListener(new OnBackPressListener() {
         @Override
         public void onBackPressed() {
             dismiss();
             getActivity().finish();
         }
    });
    return rootView;
}

}

1 个答案:

答案 0 :(得分:0)

可能是这样的吗?试一下。覆盖片段中的onKeyDown。

public boolean onKeyDown(int keyCode, KeyEvent event) {

    switch (keyCode) {
        case KeyEvent.KEYCODE_BACK:
            //Your code
            return true
}
        return false;

}