这是我试图在我的应用程序中实现的想法:
MainActivity
获取了一个名为 getServer()
的方法。现在我正在使用另一个具有(对话框)名称的类。当应用程序无法到达服务器时,我使用此对话框来 Activity ,让人们在问题解决后重试。现在我用对话框创建了一个类,我用它作为引用,问题是我可以传递上下文或其他东西,但我不知道是否可以将方法传递给对话框来打开它。
我不想在类中调用方法,在这种情况下,我应该为我构建的每个对话框创建类以在 Activity 中调用方法。我想使用一个对话框类,并向其发送方法以在用户点击"is"按钮时调用它。
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.
主要 Activity :
> 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) 创建一个接口(interface)并使您的 Activity 实现该接口(interface)
该界面应该有一个方法(例如 onRetryClick();例如),并且 Activity 应该实现该方法,并在该方法内调用您的 getServer()。
界面:
interface Listener {
onRetryClick();
}
Activity :
class MyActivity implements Listener {
...
@Override
public onRetryClick() {
getServer();
}
}
调用对话框时将 Activity 作为参数传递,并且对话框应该能够在参数中接收监听器对象
public showErrorDialog(final Listener listener) {...}
b) 您可以创建相同的监听器,并在 Activity 中创建该监听器的实例并显式定义方法
class MyActivity {
...
private Listener listener = new Listener() {
@Override
public onRetryClick() {
getServer();
}
}
}
并以与解决方案a相同的方式将监听器传递给对话框
我相信 b 更好,因为您创建一个简单的 Listener 对象并将其传递,而不是传递整个已实现的 Activity 。
还有比这些更多的解决方案,如果这没有帮助,请尝试寻找例如 EventBus 模式。
关于java - 如何将我的方法从我的 Activity 放置或发送到另一个类来调用它?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54897804/