【问题标题】:Need to show a popup/Dialog on different activities需要在不同的活动上显示一个弹出窗口/对话框
【发布时间】:2015-08-24 11:28:34
【问题描述】:

我有一个使用三个活动的应用程序。我在第一个中创建了一个线程来检查与服务器的连接,当应用程序无法访问服务器时,它会显示一个弹出窗口。

问题是,当我从 Activity1 转到 Activity2 并失去连接时,我得到了 WindowManager$BadTokenException。

我尝试过使用 PopupWindow 和 AlertDialog,但我遇到了同样的问题,我不能给他们当前的 Activity。

警报对话框:

            AlertDialog.Builder builder1 = new AlertDialog.Builder(getApplicationContext());
            builder1.setMessage("Se ha hecho el cierre diario, es necesario reiniciar la aplicación.");
            builder1.setCancelable(true);
            builder1.setPositiveButton("Ok",
                    new DialogInterface.OnClickListener() 
            {
                public void onClick(DialogInterface dialog, int id) 
                {
                    java.lang.System.exit(0);
                }
            });

            AlertDialog alert11 = builder1.create();
            alert11.show();

弹出窗口:

        final Activity context = Activity_Start.this;

        final boolean Reset = reset;

        // Inflate the popup_layout.xml
        LinearLayout viewGroup = (LinearLayout) context.findViewById(R.id.popup_mensaje_error);
        LayoutInflater layoutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        final View popup_error = layoutInflater.inflate(R.layout.mensaje_error, viewGroup, false);

        // Creating the PopupWindow
        final PopupWindow popupW_error = new PopupWindow(context);
        popupW_error.setContentView(popup_error);

在这两种情况下,我都会遇到相同的错误,我几乎 100% 确定这是因为 getApplicationContext() 不足以满足应用程序的需求。

有人可以帮助我吗?谢谢!!

【问题讨论】:

  • 使用 DialogFragment,您可以将分离附加到您喜欢的任何活动中
  • 我认为您的错误在于“最终活动上下文 = Activity_Start.this;”你不应该得到这样的上下文
  • Raghunandan,它是如何工作的? Klitos,我该怎么做?

标签: java android android-activity dialog popupwindow


【解决方案1】:

Android文档建议使用getApplicationContext();

但它不会起作用,而是在实例化 AlertDialog.Builder 或 AlertDialog 或 Dialog 时使用您当前的活动......

试试

AlertDialog.Builder builder1 = new AlertDialog.Builder(Activity_Start.this);

而不是

AlertDialog.Builder builder1 = new AlertDialog.Builder(getApplicationContext());

也可以使用

final Context context = Activity_Start.this;

而不是

final Activity context = Activity_Start.this;

对话框与此特定活动相关联,而不是与整个应用程序相关联。通常在创建范围只是活动的对象时使用 Activity.this。在创建范围超出当前活动的对象时使用应用程序上下文。

希望这会有所帮助!

【讨论】:

  • 是的,Rajesh,我就是这样,问题是线程在 Activity1 上启动,如果我在连接丢失时在 Activity2 上工作,我不知道如何发送到对话框当前活动。
  • 确实,但是在从 Activity2 调用对话框时,我得到了 WindowManager$BadTokenException。
  • 为什么要从activity2调用activity的对话框?你不能那样做。
  • 这是我的问题。线程在第一个活动中声明,并且弹出窗口应该显示在任何活动上。
  • 那么我该怎么做才能让一个进程在后台运行,如果需要,可以在任何活动上显示消息?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-09-28
  • 2012-01-04
相关资源
最近更新 更多