簡體   English   中英

Android:在助手類的任何可見活動上調用“警報”對話框?

[英]Android : Invoke the Alert dialog on any visible activity from helper class?

我有以下問題。

我試圖從簡單的幫助程序類調用警報對話框

public class NotificationHelper

因為代碼不是在活動上執行,而是在接收到推送通知之后以及活動是否在前台運行時執行。

所以我試圖通過這種方式做到這一點:

// Show dialog
                    Handler handler = new Handler(Looper.getMainLooper());
                    final String finalNotificationHeading = notificationHeading;
                    final String finalNotificationBody = notificationBody;

                    handler.post(
                            new Runnable() {
                                @Override
                                public void run() {
                                    DialogHelper.showSimpleAlert(finalNotificationHeading, finalNotificationBody, ctx.getString(R.string.positive_button_text),
                                            ctx.getString(R.string.negative_button_text), null, ctx, notificationAlertCallback);
                                }
                            }
                    );

但是我總是收到以下錯誤:

com.afollestad.materialdialogs.MaterialDialog$DialogException: Bad window token, you cannot show a dialog before an Activity is created or after it's hidden.

注意:錯誤不是由插件引起的。

我該如何解決?

非常感謝您的任何建議。

您的問題是ctx。 而當您通過時。

您應該在要創建對話框的那一刻給出它,並且它應該是當前的UI(活動,片段等)

Bad window token

說您要添加對話框的上下文當前不在屏幕上。

所以你的方法應該看起來像

NotificationHelper{
void showDialog(Activity currentActivity){
          Handler handler = new Handler(Looper.getMainLooper());
                    final String finalNotificationHeading = notificationHeading;
                    final String finalNotificationBody = notificationBody;

                    handler.post(
                            new Runnable() {
                                @Override
                                public void run() {
                                    DialogHelper.showSimpleAlert(finalNotificationHeading, finalNotificationBody, currentActivity.getString(R.string.positive_button_text),
                                            currentActivity.getString(R.string.negative_button_text), null, currentActivity, notificationAlertCallback);
                                }
                            }
                    );

}

如果在調用showDialog時不想一直傳遞currentActivity,則應該在要使用它的每個Activity的onResume中傳遞currentContext。

public void onResume(){
  super.onResume();
  NotificationHelper.ctx = this;
}

並按照您的情況使用它,但是您必須意識到,如果傳遞了錯誤的上下文(或根本不傳遞),則可能會發生錯誤的窗口令牌異常。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM