这是我要在我的应用中尝试的想法:

MainActivity具有名称为getServer()的方法。现在我正在使用另一个具有(对话框)名称的类。当应用程序无法访问服务器时,我使用此对话框进行“活动”以使人们在问题解决后重试。现在我创建了一个使用Dialogs的类,并且将其用作参考,问题是我可以传递上下文或其他东西,但是我不知道是否可以将方法传递给Dialog来打开它。

我不是要在类中调用方法,在这种情况下,我应该为我创建的每个对话框创建类以在活动中调用方法。我想使用一个对话框类,并在用户单击“是”按钮时向其发送方法以进行调用。

mPresenter:

>well there's not anything about presenter, just a simple call with retrofit
=> if response was ok, then show data(view)
=> throw or error => open Dialog(view) => this method call Dialog.Java class and ask it to call getServer() method.


主要活动:

> i want to pass getServer to Dialog.class
public void getServer() {
    mPresenter.setupServer();
}


对话类别:

    public static void RefreshDialog(final Context context) {
    AlertDialog.Builder builder = new AlertDialog.Builder(context);
    builder.setTitle("run again?");
    builder.setMessage("there's a problem with your connection or our server, wanna try again?");

    builder.setNegativeButton("yes, please.", new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {

            > want to dialog call method that received and open it if i've got yes,please!

        }
    });

    builder.setPositiveButton("nah", new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {
            dialog.dismiss();
        }
    });

    builder.show();
}

最佳答案

您可以做几件事。

a)创建一个接口,并使您的活动实现该接口

接口应具有一个方法(例如onRetryClick();),活动应实现此方法,并在该方法内部调用getServer()。

接口:

interface Listener {
  onRetryClick();
}


活动:

class MyActivity implements Listener {
  ...
  @Override
  public onRetryClick() {
    getServer();
  }
}


调用对话框时,将活动作为参数传递,并且对话框应该能够在参数中接收Listener对象

public showErrorDialog(final Listener listener) {...}


b)您可以创建相同的侦听器,并在活动中创建该侦听器的实例,以明确定义方法

class MyActivity {
  ...
  private Listener listener = new Listener() {
    @Override
    public onRetryClick() {
      getServer();
    }
  }
}


并将侦听器传递给对话框,方法与解决方案相同

我相信b会更好,因为您创建了一个简单的Listener对象并将其传递,而不是传递整个实现的活动。

除了这些解决方案之外,还有更多解决方案,例如,如果这无助于尝试查找EventBus模式。

07-24 09:37
查看更多