Question

I recently created a standard list DialogFragment to build an AlertDialog in my Activity as can be seen as the answer here:

What is the best way to recreate an AlertDialog when the screen is rotated?

Now I would like to re-use this fragment for 3 different "Pop Up" selection lists in my activity. For each of the three buttons I need to identify the calling button to determine what action to take when the item from the list is selected.

What is the best way to achieve this?

Currently I am thinking that I need to pass the calling button ID to the DialogFragment and then pass it back to the activity with the result when the dialog completes. Is there a better way to achieve this goal?

Was it helpful?

Solution

I think probably the easiest way to achieve what you're going for is to just have three different listeners inside of your DialogFragment, and then have setters for each. Then when you build the alert dialog as a fragment, you can define what the onClick method for each listener will do in the calling method. So something like this:

protected DialogInterface.OnClickListener mListener1;
protected DialogInterface.OnClickListener mListener2;
protected DialogInterface.OnClickListener mListener3;

public void setListener1(final YourDialogFragment.OnClickListener passedListener) {
    mListener1 = new DialogInterface.OnClickListener() {

        @Override
        public void onClick(DialogInterface dialog, int which) {
            listener.onClick(getActivity(), dialog, which);
        }
    };
}

Then inside of the code that calls the DialogFragment, call something like:

// Building the Dialog Fragment here

YourDialogFragment.setListener1(new YourDialogFragment.OnClickListener() {
    @Override
    public void onClick(FragmentActivity activity, DialogInterface dialog, int which) {
        // Whatever you want to happen when you click goes here
    }
});

Ideally you make some sort of helper to just take parameters so you're not explicitly calling the set methods from an activity, but that's the gist of it.

OTHER TIPS

I would recommend you to show the dialog fragment from another fragment where you can implement the onClick listeners and use setTargetFragment() to tell the dialog fragment that who it is working with..

dialogFragment.setTargetFragment(this, 0);

and use getTargetFragment() to get the parent fragment from DialogFragment.

here is some code snippets from sample programs..

       // Retrieve the progress bar from the target's view hierarchy.
       mProgressBar = (ProgressBar)getTargetFragment().getView().findViewById(
                R.id.progress_horizontal);

And also you can use setRetainInstance(true) in onCreate() method to tell the framework to try to keep this fragment around during a configuration changes

See this answer to get more idea, hope this helps..

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