有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java如何将方法名设置为新类中的参数?

我创建了一个AlertDialog类,该类有一个名为OnYesClicked()的方法,当单击肯定按钮时将调用该方法。但是,我需要在同一个活动中多次使用此AlertDialog类,因此我想将名称OnYesClicked()设置为参数,以便为不同的对话框调用正确的方法,否则可能会调用错误的方法或两个方法。在搜索了包括一个here在内的其他类似问题后,我不太确定如何解决这个问题 完整代码如下:


import 安卓.app.AlertDialog;
import 安卓.app.Dialog;
import 安卓.content.Context;
import 安卓.content.DialogInterface;
import 安卓.os.Bundle;
import 安卓.widget.Toast;
import 安卓x.annotation.NonNull;
import 安卓x.annotation.Nullable;
import 安卓x.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");
        }
    }
}

使用该类时,我还需要调用以下命令

  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
 }

共 (1) 个答案

  1. # 1 楼答案

    不要在ExampleDialogonAttach()中设置侦听器,而是从外部传递ExampleDialogListener的实例。在活动中维护ExampleDialogListener的不同侦听器实例,这将使您能够控制单个ExampleDialog的回调

    像这样:

    步骤1:删除在ExampleDialogonAttach()中设置ExampleDialogListener的语句

    @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");
        }*/
    }
    

    第2步:在ExampleFragment中添加一个public方法来初始化ExampleDialogListener

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

    步骤3:在方法newInstance()中传递ExampleDialogListener的实例,并在那里设置侦听器

    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;
    
    }
    

    第4步:创建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
        }
    };
    

    最后,为每个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");
    }