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?
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
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With