Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Activity to wait for Dialog Fragment input

Tags:

android

dialog

I have created a DialogFragment with a custom AlertDialog that I need to show on several points of my application. This dialog asks for the user to input some data.

I would like to find a way to make the activity where the dialog is called upon to wait for the users input and then perform a variable action when the user presses the ok button (or nothing if he presses cancel).

AFAIK there's no "modal dialog" in Android so what would be the proper way to achieve this (pretty usual) kind of behavior?

like image 921
Gabriel Sanmartin Avatar asked Mar 24 '23 17:03

Gabriel Sanmartin


1 Answers

To allow a Fragment to communicate up to its Activity, you can define an interface in the Fragment class and implement it within the Activity.

public class MyDialogFragment extends DialogFragment {
OnDialogDismissListener mCallback;

// Container Activity must implement this interface
public interface OnDialogDismissListener {
    public void onDialogDismissListener(int position);
}

@Override
public void onAttach(Activity activity) {
    super.onAttach(activity);

    // This makes sure that the container activity has implemented
    // the callback interface. If not, it throws an exception
    try {
        mCallback = (OnDialogDismissListener) activity;
    } catch (ClassCastException e) {
        throw new ClassCastException(activity.toString()
                + " must implement OnDialogDismissListener");
    }
}


    ...
}

In dialog Ok listener add

mCallback.onDialogDismissListener(position);

In your activity

public static class MainActivity extends Activity
        implements MyDialogFragment.OnDialogDismissListener{
    ...

    public void onDialogDismissListener(int position) {
        // Do something here to display that article
    }
}
like image 118
Tarun Avatar answered Mar 31 '23 22:03

Tarun