Skip to content Skip to sidebar Skip to footer

Communicating My Dialog With Main Activity

I have read a lot of tutorials on how to communicate a FragmentDialog with the activity but I seem be unable to adapt them to my project. What I want to do is simple, when the user

Solution 1:

Create an Interface and implement that in the Activity class and pass its reference to the Dialog class. When user clicks the dialog button call the method using the interface.

Do something like this

public interface OnMyDialogClick
{
    public abstract void onPositiveButtonClick();
}

Your activity

if(id == R.id.menu_change_date){
        DialogFragment dialog = new Dialog_Elegir_Mes(new OnMyDialogClick()
        {
              @Override
              public void onPositiveButtonClick()
              {
                   //Call your activity method here
              }
        });
        dialog.show(getSupportFragmentManager(),"Elegir Mes");
}

Your Dialog class

public class Dialog_Elegir_Mes extends DialogFragment {
private OnMyDialogClick _onMyDialogClick = null;
public Dialog_Elegir_Mes(OnMyDialogClick ref)
{
    _onMyDialogClick = ref;
}

@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
    // Build the dialog and set up the button click handlers
    AlertDialog.Builder adb = new AlertDialog.Builder(getActivity());
    LayoutInflater inflater = getActivity().getLayoutInflater();

    final View v = inflater.inflate(R.layout.diag_select_month,null);


    adb.setTitle("Elegir Mes");

    adb.setView(v)
            .setPositiveButton("Aceptar", new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int id) {

                      _onMyDialogClick.onPositiveButtonClick();
                }
            })
            .setNegativeButton("Cancelar", new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int id) {
                    Dialog_Elegir_Mes.this.getDialog().cancel();
                }
            });


    return adb.create();
}
}

Post a Comment for "Communicating My Dialog With Main Activity"