I use the following code to open a dialog fragment in which the user enter some text
var transaction = FragmentManager.BeginTransaction(); var dialogFragment = new userDataModal(); dialogFragment.Show(transaction, "userDataModal");
There's an edit text element in the dialog fragment, how can retrieve the value of this edit text in my activity?
Posts
In your DialogFragment implementation, expose an event that you can subscribe to from the Activity which will return the result of the EditText.
Example in your DialogFragment class declare the event:
Then override the OnDismiss method to raise the event for those that are subscribed to it:
Notice that I am using a custom class to pass data back:
From the Activity, instantiate the custom dialog, subscribe to the DialogClosed event, and launch the dialog:
And then check the return values in the object passed into the OnDialogClosed event from your DialogFragment class:
This worked excellent for me, except I didn't use the DialogEventArgs, because I didn't need to pass anything back to the activity. I used Lori's example and did the following:
In my dialog:
public event EventHandler DialogClosed;
overriding OnDismiss:
public override void OnDismiss(IDialogInterface dialog)
{
base.OnDismiss(dialog);
if (DialogClosed != null)
{
DialogClosed(this, null);
}
}
In my Activity:
dialogQuantity.DialogClosed += DialogQuantity_DialogClosed;
private void DialogQuantity_DialogClosed(object sender, EventArgs e)
{
//stuff to do
}
The "EventHandler" pattern won't work if your dialog maintain state on screen rotations. The activity will get destroyed, and the eventhandler will be calling on a dangling activity. I think the best approach is to use the well tested pattern of creating an interface, implement it on the calling activity and get a reference to it on the OnAttach method override.