简体   繁体   中英

Invoking methods from MainActivity within the onClick methods of a DialogFragment

I'm trying to use a DialogFragment to show a Dialog within my MainActivity. Depending on the user's reaction to the dialog I want to invoke methods defined in my MainActivity.java file (eg onActivityResult , but ideally also customized methods).

Following a reply by ashishduh on this question, I defined the DialogFragment as follows (in a seperate java file):

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;

public class YesNoDialog extends DialogFragment {
public static final String ARG_TITLE = "YesNoDialog.Title";
public static final String ARG_MESSAGE = "YesNoDialog.Message";

public YesNoDialog() {}

@Override
public Dialog onCreateDialog(Bundle savedInstanceState)
{   Bundle args = getArguments();
    String title = args.getString(ARG_TITLE);
    String message = args.getString(ARG_MESSAGE);

    return new AlertDialog.Builder(getActivity())
            .setTitle(title)
            .setMessage(message)
            .setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener()
            {
                @Override
                public void onClick(DialogInterface dialog, int which)
                {
                    getTargetFragment().onActivityResult(getTargetRequestCode(), Activity.RESULT_OK, null);
                }
            })
            .setNegativeButton(android.R.string.no, new DialogInterface.OnClickListener()
            {
                @Override
                public void onClick(DialogInterface dialog, int which)
                {
                    getTargetFragment().onActivityResult(getTargetRequestCode(), Activity.RESULT_CANCELED, null);
                }
            })
            .create();
}
}

Correspondingly, I try to start it from the MainActivity like this:

    public void openYesNoDialog (View view) {
    DialogFragment dialog = new YesNoDialog();
    Bundle args = new Bundle();
    args.putString(YesNoDialog.ARG_TITLE, "title");
    args.putString(YesNoDialog.ARG_MESSAGE, "message");
    dialog.setArguments(args);
    dialog.setTargetFragment(this, YES_NO_CALL);
    dialog.show(getSupportFragmentManager(), "tag");
}

where openYesNoDialog is triggered by a button in the activity_main.xml layout file.

I am facing the problem that setTargetFragment(this, YES_NO_CALL) is not working, since "this" corresponds to my MainActivity, but setTargetFragment is (naturally) expecting a Fragment and no Activity. The problem is that I do not know what to reference in the first argument instead because apart from the DialogFragment I am trying to build I have made absolutely no use of Fragments in my code. So I am wondering which of the following strategies you would encourage to fix my issue (not even sure if all of them might possibly work):

1.) Use a method similar to setTargetFragment which allows setting a target Activity. (sort of a "setTargetActivity" method; this solution sounds easiest to me if such a thing exists, but I haven't found anything similar yet).

2.) Write everything in terms of Fragments and have something like a "MainFragment" instead of a MainActivity. I could then easily reference this "MainFragment" as a reasonable target fragment with "this".

3.) Use a completely different approach (eg not putting the methods in the activity but in an interface both activity and fragment implement, but actually I also want to make use of eg TextViews of the activity inside of the DialogFragment, so I think this might be a problem)

I am very thankful for any help.

One final comment: Note that I am using the v4 support libraries in my imports to support backward compatibility as suggested in the Android tutorials on Dialogs.

This is for example why I needed to use getSupportFragmentManager() instead of getFragmentManager() to make work what is already working right now. So that's the reason for my slight modifications of the code I have been referring to with the hyperlink.

getTargetFragment and setTargetFragment both we should use for communication between Fragment to Fragment,

For Activity to Fragment communication, you can use 2 ways

  1. You can use interface for communication

  2. You can use Local broadcast

Interface communication

Create one interface in dialog fragment,

public class YesNoDialog extends DialogFragment {
   public interface OnDialogActionListener {
       public void onClickDialog();
   }

   private OnDialogActionListener mListener;

   @Override
   public void onAttach(Context context) {
       mListener = (OnDialogActionListener) context;
   }

   // Your code

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

}

And in Your activity you can implement and override the function, you will get callback in your Activty.

You can simply use interface for the same. Just define interface in a separate class and declare method as onClickEvent/onSuccess according to you and override it in your activity and perform your task in your activity in the method. And call this method from your dialog on yes/no click buttons.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM