【问题标题】:How to set method name as a parameter in a new class?如何将方法名称设置为新类中的参数?
【发布时间】:2020-04-12 01:56:26
【问题描述】:

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


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

在使用类的时候,我还需要调用如下

  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
 }

【问题讨论】:

    标签: java android class methods parameters


    【解决方案1】:

    更改回调方法的定义以包含一个标记作为参数。每次调用该方法时,使用不同的标签来标识您正在使用它的对话框。在回调的实现中创建一个开关来识别回调的来源并相应地执行需要执行的操作。

    定义:

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

    触发器:

    listener.onYesClicked("dialogA");
    

    实施:

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

    【讨论】:

      【解决方案2】:

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

      像这样:

      步骤1:删除在ExampleDialog的onAttach()中设置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");
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2012-10-15
        • 2017-10-12
        • 1970-01-01
        • 1970-01-01
        • 2019-09-10
        • 1970-01-01
        • 2011-06-25
        相关资源
        最近更新 更多