[英]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.