Android 对话框自行消失

Android dialog disappears on its own(Android 对话框自行消失)
本文介绍了Android 对话框自行消失的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用以下代码来创建自己的对话框:

I'm using the following code to create my own dialog:

public void ShowMessageDialog(String str){
    AlertDialog.Builder builder = new AlertDialog.Builder(this);
    builder.setMessage(str);
    builder.setCancelable(false);
    builder.setNeutralButton("Ok", new DialogInterface.OnClickListener() {          
        @Override
        public void onClick(DialogInterface dialog, int which) {
            dialog.dismiss();
        }
    });
    AlertDialog alert = builder.create();
    alert.show();
}

它工作正常,但在此函数中使用时,对话框会自行消失:

It works fine but it appears the Dialog disappears on it's own when used inside this function:

public void test(String str){
    ShowMessageDialog("About to start new activity");
    Intent intent = new Intent(this,PageViewer.class);
    startActivity(intent);
}

似乎新活动已创建并且显然摆脱了对话框.但为什么?活动不应该在打开新活动之前停止吗?

It seems that the new activity is created and obviously gets rid of the dialog. But why? Shouldn't the activity stop before opening the new one?

谢谢!

推荐答案

即将触发的 Intent 不会等待您的对话框被取消.因此,在显示对话框后,新的活动就开始了.你可以像这样完成你想要的:

Intent which is about to fire doesn't wait for your dialog to be canceled. So, right after dialog is shown, new Activity is started. You could accomplish what you want like this:

public void ShowMessageDialog(String str){
    AlertDialog.Builder builder = new AlertDialog.Builder(this);
    builder.setMessage(str);
    builder.setCancelable(false);
    builder.setNeutralButton("Ok", new DialogInterface.OnClickListener() {          
        @Override
        public void onClick(DialogInterface dialog, int which) {
            dialog.dismiss();
            Intent intent = new Intent(this,PageViewer.class);
            startActivity(intent);
        }
    });
    AlertDialog alert = builder.create();
    alert.show();
}

public void test(String str){
    ShowMessageDialog("About to start new activity");
}

这篇关于Android 对话框自行消失的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

How to target newer versions in .gitlab-ci.yml using auto devops (java 11 instead of 8 and Android 31 instead of 29)(如何在.gitlab-ci.yml中使用自动开发工具(Java 11而不是8,Android 31而不是29)瞄准较新的版本)
Android + coreLibraryDesugaring: which Java 11 APIs can I expect to work?(Android+core LibraryDesugering:我可以期待哪些Java 11API能够工作?)
How to render something in an if statement React Native(如何在If语句中呈现某些内容Reaction Native)
How can I sync two flatList scroll position in react native(如何在本机Reaction中同步两个平面列表滚动位置)
Using Firebase Firestore in offline only mode(在仅脱机模式下使用Firebase FiRestore)
Crash on Google Play Pre-Launch Report: java.lang.NoSuchMethodError(Google Play发布前崩溃报告:java.lang.NoSuchMethodError)