I have Fragment that extends DialogFragment and I have a custom layout for it which contains two edittexts and two buttons - ok and cancel. My dialog displays just fine, using the onCreateView method for specifying the layout, but I don't know how to handle button clicks. Inside the onCreateView method, button.setOnClickListener doesn't work. This may have a simple solution, but I am stuck for several hours. I would very much appreciate an advice or example code.
P.S I don't want to use AlertDialog, because in this case when clicking on the ok button, the dialog automatically dismisses itself, and I can't do a validation on the edittext's (example: when the user presses ok button and the edittext's are empty I don't want the dialog to disappear). That is way I went with the option for creating a custom dialog and easily manage the buttons behavior.
This is the code for a Dialog I'm using (the actual GUI for the dialog is defined in the layout resource confirm_dialog.xml):
public class ConfirmDialog extends DialogFragment {
public static String TAG = "Confirm Dialog";
public interface ConfirmDialogCompliant {
public void doOkConfirmClick();
public void doCancelConfirmClick();
}
private ConfirmDialogCompliant caller;
private String message;
public ConfirmDialog(ConfirmDialogCompliant caller, String message){
super();
this.caller = caller;
this.message = message;
}
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
final View view = inflater.inflate(R.layout.confirm_dialog, container, false);
getDialog().requestWindowFeature(Window.FEATURE_NO_TITLE);
((TextView) view.findViewById(R.id.textview_confirm)).setText(message);
((Button) view.findViewById(R.id.ok_confirm_button)).setOnClickListener(new OnClickListener() {
public void onClick(View v) {
// When button is clicked, call up to owning activity.
caller.doOkConfirmClick();
}
});
((Button) view.findViewById(R.id.cancel_confirm_button)).setOnClickListener(new OnClickListener() {
public void onClick(View v) {
// When button is clicked, call up to owning activity.
caller.doCancelConfirmClick();
}
});
return view;
}
}
The dialog is created with the following lines
confirm_dialog = new ConfirmDialog(this, message);
confirm_dialog.show(getActivity().getSupportFragmentManager(), ConfirmDialog.TAG);
The interface definition is used to assure that the caller (Fragment or Activity) implements the methods to handle the events thrown by the controller. That is, a Fragment or Activity calling this dialog must implement the given interface.
Maybe there is a better solution but this is the one I figured out. Hope it helps!