[英]How to allow a non-activity to display dialog on activity?
这个问题与过去提出的问题非常相似,但是请耐心等待,因为它仍然是一个独特的问题。 基本上,我有一个获得应用程序许可权的类,并且如果用户没有运行互联网,则当自动登录屏幕出现时,它将停留在加载中。 因此,我想做的是显示一个对话框消息,用户将单击“确定”关闭该应用程序。 对于对话框,我需要上下文,并且必须在主线程上运行。 我发布了代码的图像,因为我想向您展示runOnUIThread
是红色的。 这是我从Android Studio获得的错误
无法解析方法runOnUIThread。
这就是我所拥有的
问题:由于某种原因, runOnUIThread
不可用。 有没有人提出反对的建议,或者我有这个问题的原因?
这是代码:
public void alert() {
new Thread()
{
public void run()
{
application.runOnUiThread(new Runnable() // application is the context of my current activity.
{
public void run() //I display my alert Dialog here.
{
AlertDialog build= new AlertDialog.Builder(application.getApplicationContext())
.setTitle("Error")
.setMessage("Sorry there seems to be a problem with the service. Please check to make sure you have a stable internet connection. ")
.setPositiveButton("Ok, I understand.", (dialog, which) -> System.exit(0))
.show();
build.setCancelable(false);
Button positive= build.getButton(DialogInterface.BUTTON_POSITIVE);
positive.setTextColor(application.getResources().getColor(R.color.buttonPrimaryColor));
positive.setTypeface(Typeface.defaultFromStyle(Typeface.BOLD));
}
});
}
}.start();
这就是我过去如何将其与Toast一起使用的方式。
public void shortToast(String msg) {
Observable.just(msg)
.observeOn(AndroidSchedulers.mainThread())
.subscribe(message -> {
Toast.makeText(application, message, Toast.LENGTH_SHORT).show();
});
}
// In the main method
shortToast("Sorry an error occured");
由于某些原因,runOnUIThread不可用
您尝试调用的方法是runOnUiThread()
。 那是一个关于Activity
的方法。 无论是什么application
,它都不是Activity
。
有人反对吗
将此代码移到Activity
。 通常,弹出窗口(对话框,小吃店等)应由“ Activity
显示。 而且只有Activity
可以显示Dialog
,例如AlertDialog
。
尝试使用活动在UI而非应用程序上运行
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.