0

User can click on the DialogFragment's "Cancel" button or the "OK" button on the screen or on the Back Button on their device. The code for the Cancel and OK buttons work fine. When clicking the Back Button, the goal is to close (dismiss) the DialogFragement and return to the previous activity. My code for the Back Button is not working, please advise.

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

}

AJW
  • 1,578
  • 3
  • 36
  • 77
  • possible duplicate of [Detect back button but don't dismiss dialogfragment](http://stackoverflow.com/questions/21307858/detect-back-button-but-dont-dismiss-dialogfragment) – Nir Alfasi Jul 17 '15 at 17:29

1 Answers1

0

May be smthing like this? Give a try. Override onKeyDown in your fragment.

public boolean onKeyDown(int keyCode, KeyEvent event) {

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

}

sttimchenko
  • 401
  • 3
  • 15
  • What about ACTION_UP and ACTION_Down though. Here's an example I had to use in other code that went beyond KEYCODE_BACK. Thoughts? public boolean onKeyPreIme(int keyCode, @NonNull KeyEvent event) { if(event.getKeyCode()==KeyEvent.KEYCODE_BACK) { if(event.getAction()== KeyEvent.ACTION_DOWN && event.getRepeatCount()==0) { getKeyDispatcherState().startTracking(event, this); return true; } ... – AJW Jul 17 '15 at 18:08