【问题标题】:Android Dialog from different class来自不同类的Android Dialog
【发布时间】:2020-09-06 02:55:26
【问题描述】:
我正在构建一个 android 应用程序并希望从非活动类调用一个对话框(这是在后台发生的)。
我希望在特定活动上显示对话框,但为了让其他类调用此函数,它必须是静态的,但我不能从静态上下文调用 getSupportFragmentManager()。
有解决这个问题的方法吗?这是我试图使用的代码。
public static void method_invoked_returned_null(String response) {
ErrorDialog errorDialog = new ErrorDialog();
ErrorDialog.errorType = "Response Command Error";
ErrorDialog.errorDialogMessage = "Error in Invoking " + response
+ ". Do you want to continue?";
errorDialog.show(getSupportFragmentManager(), "Wrong Response Dialog");
}
【问题讨论】:
标签:
android
user-interface
android-activity
static
dialog
【解决方案1】:
你有两个解决办法
1:使用广播接收器并在您的活动中的 onResume 中注册广播并在 onPause 中取消注册。
2:您可以在活动中添加静态字段实例并在 onResume 中设置值并在 onPause 中将其删除
private static AppCompatActivity instance;
@Override
protected void onResume() {
super.onResume();
instance = this;
}
@Override
protected void onPause() {
super.onPause();
instance = null;
}
public static void method_invoked_returned_null(String response) {
if (instance == null)
return;
instance.runOnUiThread(new Runnable() {
@Override
public void run() {
ErrorDialog errorDialog = new ErrorDialog();
ErrorDialog.errorType = "Response Command Error";
ErrorDialog.errorDialogMessage = "Error in Invoking " + response
+ ". Do you want to continue?";
errorDialog.show(instance.getSupportFragmentManager(), "Wrong Response Dialog");
}
});
}