简体   繁体   中英

How to set method name as a parameter in a new class?

I have created a AlertDialog class that has a method called OnYesClicked() which will be called when the positive button is clicked. However, I need to use this AlertDialog class more than once in the same activity, so I want to set the name OnYesClicked() as a parameter, so that I can call the correct method for different dialogs, or else the wrong method or both methods may be called. I am not too sure on how to solve this problem after searching up other similar questions including one here The full code is below:


import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Bundle;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatDialogFragment;

public class ExampleDialog extends AppCompatDialogFragment {

    private static final String ARGUMENT_TITLE = "title";
    private static final String ARGUMENT_POSITIVE = "positive";
    private static final String ARGUMENT_MESSAGE = "message";
    private static final String ARGUMENT_POSITIVE_TEXT = "positive_text";
    private static final String ARGUMENT_NEGATIVE = "negative";
    private static final String ARGUMENT_NEGATIVE_TEXT = "negative_text";

    private ExampleDialogListener listener;

    private String title;
    private String message;
    private String positive;
    private String positivetext;
    private String negative;
    private  String negativetext;

    public static ExampleDialog newInstance(String title, String message, String positive,//request input from user when call, save as string
                                            String positivetext, String negative, String negativetext) {
        Bundle args = new Bundle();
        // Store all arguments into bundle.
        args.putString(ARGUMENT_TITLE, title); //save as name ARGUMENT_TITLE, value is the user input title, shove inside a bundle called args
        args.putString(ARGUMENT_POSITIVE, positive);
        args.putString(ARGUMENT_MESSAGE, message);
        args.putString(ARGUMENT_POSITIVE_TEXT, positivetext);
        args.putString(ARGUMENT_NEGATIVE, negative);
        args.putString(ARGUMENT_NEGATIVE_TEXT, negativetext);
        ExampleDialog fragment = new ExampleDialog();
        fragment.setArguments(args); //put whole bundle into fragment
        return fragment; //fragment is given to code that call this newInstance
    }


    @Override
    public Dialog onCreateDialog(@Nullable Bundle savedInstanceState)  {

        title = getArguments().getString(ARGUMENT_TITLE); //using key, retrieve string value (user input), set as "title"
        positive = getArguments().getString(ARGUMENT_POSITIVE);
        message = getArguments().getString(ARGUMENT_MESSAGE);
        positivetext = getArguments().getString(ARGUMENT_POSITIVE_TEXT);
        negative = getArguments().getString(ARGUMENT_NEGATIVE);
        negativetext = getArguments().getString(ARGUMENT_NEGATIVE);

        AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
        builder.setTitle(title)
                .setMessage(message)
                .setNegativeButton(negative, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        Toast toast = Toast.makeText(getContext(), negativetext, Toast.LENGTH_SHORT);
                        toast.show();
                    }
                })
                .setPositiveButton(positive, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        Toast toast = Toast.makeText(getContext(), positivetext, Toast.LENGTH_SHORT);
                        toast.show();
                        listener.onYesClicked(); //listens for method onYesClicked(), need declare in code when call this class
                    }
                });
        return builder.create();
    }

    public interface ExampleDialogListener {
        void onYesClicked();
    }

    @Override
    public void onAttach(@NonNull Context context) {
        super.onAttach(context);

        try {
            listener = (ExampleDialogListener) context;
        } catch (ClassCastException e) {
            throw new ClassCastException(context.toString()
                    + "must implement ExampleDialogListener");
        }
    }
}

when using the class, I need to also call the following

  public void openDialog() {
          ExampleDialog dialog = ExampleDialog.newInstance("Title", "message",
                                                      "positive","positive text",
                                                      "negative","negative text");
          dialog.show(getSupportFragmentManager(),"example dialog");}
 @Override
 public void onYesClicked() {
    //what happens if yes is clicked
 }

Change the definition of your callback method to include a tag as a parameter. Each time you call the method use a different tag to identify the dialog you're using it from. Inside the implementation of the callback create a switch to identify where the callback is coming from and do what needs to be done accordingly.

Definition:

public interface ExampleDialogListener {
        void onYesClicked(String tag);
    }

Trigger:

listener.onYesClicked("dialogA");

Implementation:

@Override
 public void onYesClicked(String tag) {
    //what happens if yes is clicked
    Switch (tag) {
        case “dialogA”:
            //method for dialog A
        break;
        case “dialogB”:
            //method for dialog B
        break;
    }
 }

Instead of setting the listener in the onAttach() of ExampleDialog , pass the instance of ExampleDialogListener from outside. Maintain different listeners instances of ExampleDialogListener in an activity, which will give you control to callbacks of individual ExampleDialog .

Like this:

STEP 1: Remove the statement that sets the ExampleDialogListener in the onAttach() of ExampleDialog

@Override
public void onAttach(@NonNull Context context) {
    super.onAttach(context);

    /*try {
        listener = (ExampleDialogListener) context;
    } catch (ClassCastException e) {
        throw new ClassCastException(context.toString()
                + "must implement ExampleDialogListener");
    }*/
}

STEP 2: Add a public Method in the ExampleFragment that initializes the ExampleDialogListener .

public void setListener(ExampleDialogListener listener) {
    this.listener = listener;
}

STEP 3: Pass the instance of ExampleDialogListener in the method newInstance() and set the listener there.

public static ExampleDialog newInstance(
    String title,
    String message,
    String positive,
    String positivetext,
    String negative,
    String negativetext,
    ExampleDialogListener listener /* Pass the Listener from outside */
) {

    Bundle args = new Bundle();

    args.putString(ARGUMENT_TITLE, title);
    args.putString(ARGUMENT_POSITIVE, positive);
    args.putString(ARGUMENT_MESSAGE, message);
    args.putString(ARGUMENT_POSITIVE_TEXT, positivetext);
    args.putString(ARGUMENT_NEGATIVE, negative);
    args.putString(ARGUMENT_NEGATIVE_TEXT, negativetext);

    ExampleDialog fragment = new ExampleDialog();
    fragment.setArguments(args);
    fragment.setListener(listener); // <---- SET THE LISTENER HERE

    return fragment;

}

STEP 4: Create the multiple instances of ExampleDialogListener .

private ExampleDialog.ExampleDialogListener listener1 = new ExampleDialog.ExampleDialogListener() {
    @Override
    public void onYesClicked() {
        // Your Implementation
    }
};

private ExampleDialog.ExampleDialogListener listener2 = new ExampleDialog.ExampleDialogListener() {
    @Override
    public void onYesClicked() {
        // Your Implementation
    }
};

private ExampleDialog.ExampleDialogListener listener3 = new ExampleDialog.ExampleDialogListener() {
    @Override
    public void onYesClicked() {
        // Your Implementation
    }
};

Finally, set different listeners to each ExampleDialog .

public void openDialog() {
    ExampleDialog dialog1 = ExampleDialog.newInstance(
        "Title",
        "message",
        "positive",
        "positive text",
        "negative",
        "negative text",
        listener1
    );

    ExampleDialog dialog2 = ExampleDialog.newInstance(
        "Title",
        "message",
        "positive",
        "positive text",
        "negative",
        "negative text",
        listener2
    );

    ExampleDialog dialog3 = ExampleDialog.newInstance(
        "Title",
        "message",
        "positive",
        "positive text",
        "negative",
        "negative text",
        listener3
    );

    dialog1.show(getSupportFragmentManager(),"example dialog");
    dialog2.show(getSupportFragmentManager(),"example dialog");
    dialog3.show(getSupportFragmentManager(),"example dialog");
}

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