Question

I used the documentation here to create a dialogfragment. The code is :

public static MyAlertDialogFragment newInstance(int title) {
    MyAlertDialogFragment frag = new MyAlertDialogFragment();
    Bundle args = new Bundle();
    args.putInt("title", title);
    frag.setArguments(args);
    return frag;
}

@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
    int title = getArguments().getInt("title");

    return new AlertDialog.Builder(getActivity())
            .setIcon(R.drawable.alert_dialog_icon)
            .setTitle(title)
            .setPositiveButton(R.string.alert_dialog_ok,
                new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int whichButton) {
                        ((FragmentAlertDialog)getActivity()).doPositiveClick();
                    }
                }
            )
            .setNegativeButton(R.string.alert_dialog_cancel,
                new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int whichButton) {
                        ((FragmentAlertDialog)getActivity()).doNegativeClick();
                    }
                }
            )
            .create();
}}

the dialogfragment here is associated with only the activity FragmentAlertDialog. Is there any way to associate it with multiple activities? I have my calling activity name in onCreateDialog by passing it through setArguements(). Any way to use it ? I checked this question and was hoping for a confirmation/better way.

Was it helpful?

Solution

Instead of having a FragmentAlerDialog activity, you could define somewhere an interface (by somewhere I mean either a public static interface in DialogFragment class, or a separate public interface Java file), and any Activity that wishes to display the dialog could implement this interface.

One common practice that I use is to have a root Activity for all my project activities. Make that root activity implement that interface and then you can display that DialogFragment from anywhere.

OTHER TIPS

I'll just post what edits I made in my code, all credits to @gunar,

create new DialogImplement.java as:

package com.example.test;
public interface DialogImplement
{

    public void doPositiveClick();

}

Add @Override in activity code before the implementation of doPositiveClick(), for eg:

@Override
public void doPositiveClick() 
{
    //do what you want to do

}

make sure your activity implements DialogImplement, and modify code in the question as:

((DialogImplement)getActivity()).doPositiveClick(); //Or negative click code

Hope this helps..Cheers :]

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top