Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pass Data From Activity To Dialog

Tags:

android

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

like image 272
jsw Avatar asked May 25 '11 13:05

jsw


People also ask

How pass data from activity to dialog fragment?

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.

How do you pass data to dialog box in flutter?

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.

What is dialog fragment?

A DialogFragment is a special fragment subclass that is designed for creating and hosting dialogs.


2 Answers

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.

like image 45
Olegas Avatar answered Sep 18 '22 11:09

Olegas


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);
         }             
    }
}
like image 141
inazaruk Avatar answered Sep 19 '22 11:09

inazaruk