I am looking for a way to pass data from an activity onto a dialog box. I am trying to call showDialog(int);
, however i don't see a way to pass any data to the dialog box.
I need to pass a string to the dialog box in order to display a confirmation :)
Cheers
In order to pass the data to the DialogFragment class, we can simply set the data using setArguments on the instance of the class. In order to return the data from the DialogFragments to the Activity/another fragment, we need to create our custom interface.
Flutter is written with Dart, so this is where I would start. Now, to answer your question, for your case in order to pass information to the Stateless Dialog Box, the easiest way is to use a constructor. Then when you invoke the Dialogue Widget, you simply pass this information into it directly.
A DialogFragment is a special fragment subclass that is designed for creating and hosting dialogs.
When you are doing showDialog(int) the Activity's onCreateDialog method is called. There you must create a dialog instance and return it, and it will be shown.
Then you are creating a dialog, you have a full access to your class' fields and can use values of them to adjust parameters and content of created dialog.
If you are targeting Android 2.2 (API Level 8 or higher) you can use
public final boolean showDialog (int id, Bundle args)
And pass your arguments in Bundle
. See documentation.
If you want to support older Android versions, you should save your arguments in Activity
class members and then access them from your onPrepareDialog
function. Note that onCreateDialog
won't fit your needs as it's called only once for dialog creation.
class MyActivity {
private static int MY_DLG = 1;
private String m_dlgMsg;
private showMyDialog(String msg){
m_dlgMsg = msg;
showDialog(MY_DLG);
}
private doSomething() {
...
showMyDlg("some text");
}
protected void onCreateDialog(int id){
if(id == MY_DLG){
AlertDialog.Builder builder = new AlertDialog.Builder(this);
....
return builder.create();
}
return super.onCreateDialog(id);
}
@Override
protected void onPrepareDialog (int id, Dialog dialog){
if(id == MY_DLG){
AlertDialog adlg = (AlertDialog)dialog;
adlg.setMessage(m_dlgMsg);
} else {
super.onPrepareDialog(id, dialog);
}
}
}
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