如何在 Android 上显示是/否对话框?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2478517/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-20 06:00:32  来源:igfitidea点击:

How to display a Yes/No dialog box on Android?

androidandroid-alertdialog

提问by Solo

Yes, I know there's AlertDialog.Builder, but I'm shocked to know how difficult (well, at least not programmer-friendly) to display a dialog in Android.

是的,我知道有 AlertDialog.Builder,但我很震惊地知道在 Android 中显示对话框有多么困难(好吧,至少对程序员不友好)。

I used to be a .NET developer, and I'm wondering is there any Android-equivalent of the following?

我曾经是 .NET 开发人员,我想知道是否有以下 Android 等效项?

if (MessageBox.Show("Sure?", "", MessageBoxButtons.YesNo) == DialogResult.Yes){
    // Do something...
}

回答by Steve Haley

AlertDialog.Builder really isn't that hard to use. It's a bit intimidating at first for sure, but once you've used it a bit it's both simple and powerful. I know you've said you know how to use it, but here's just a simple example anyway:

AlertDialog.Builder 真的不难使用。一开始肯定有点吓人,但是一旦你使用过它,它既简单又强大。我知道你说过你知道如何使用它,但这里只是一个简单的例子:

DialogInterface.OnClickListener dialogClickListener = new DialogInterface.OnClickListener() {
    @Override
    public void onClick(DialogInterface dialog, int which) {
        switch (which){
        case DialogInterface.BUTTON_POSITIVE:
            //Yes button clicked
            break;

        case DialogInterface.BUTTON_NEGATIVE:
            //No button clicked
            break;
        }
    }
};

AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setMessage("Are you sure?").setPositiveButton("Yes", dialogClickListener)
    .setNegativeButton("No", dialogClickListener).show();

You can also reuse that DialogInterface.OnClickListenerif you have other yes/noboxes that should do the same thing.

DialogInterface.OnClickListener如果您有其他是/否框应该做同样的事情,您也可以重复使用它。

If you're creating the Dialog from within a View.OnClickListener, you can use view.getContext()to get the Context. Alternatively you can use yourFragmentName.getActivity().

如果您从 a 创建 Dialog View.OnClickListener,则可以使用view.getContext()来获取上下文。或者,您可以使用yourFragmentName.getActivity().

回答by nikki

Try this:

尝试这个:

AlertDialog.Builder builder = new AlertDialog.Builder(this);

builder.setTitle("Confirm");
builder.setMessage("Are you sure?");

builder.setPositiveButton("YES", new DialogInterface.OnClickListener() {

    public void onClick(DialogInterface dialog, int which) {
        // Do nothing but close the dialog

        dialog.dismiss();
    }
});

builder.setNegativeButton("NO", new DialogInterface.OnClickListener() {

    @Override
    public void onClick(DialogInterface dialog, int which) {

        // Do nothing
        dialog.dismiss();
    }
});

AlertDialog alert = builder.create();
alert.show();

回答by Erich Douglass

Steve H's answer is spot on, but here's a bit more information: the reason that dialogs work the way they do is because dialogs in Android are asynchronous (execution does not stop when the dialog is displayed). Because of this, you have to use a callback to handle the user's selection.

Steve H 的回答是正确的,但这里有更多信息:对话框以它们的方式工作的原因是因为 Android 中的对话框是异步的(显示对话框时执行不会停止)。因此,您必须使用回调来处理用户的选择。

Check out this question for a longer discussion between the differences in Android and .NET (as it relates to dialogs): Dialogs / AlertDialogs: How to "block execution" while dialog is up (.NET-style)

查看此问题以了解 Android 和 .NET 之间的差异(因为它与对话框有关)的更长时间讨论: Dialogs / AlertDialogs: How to "block execution" while dialog is up (.NET-style)

回答by hash

This is working for me:

这对我有用:

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

    builder.setTitle("Confirm");
    builder.setMessage("Are you sure?");

    builder.setPositiveButton("YES", new DialogInterface.OnClickListener() {

        public void onClick(DialogInterface dialog, int which) {

            // Do nothing, but close the dialog
            dialog.dismiss();
        }
    });

    builder.setNegativeButton("NO", new DialogInterface.OnClickListener() {

        @Override
        public void onClick(DialogInterface dialog, int which) {

            // Do nothing
            dialog.dismiss();
        }
    });

    AlertDialog alert = builder.create();
    alert.show();

回答by Jawad Zeb

Asking a Person whether he wants to call or not Dialog..

询问一个人他是否想打电话给 Dialog..

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageView;
import android.widget.Toast;

public class Firstclass extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {    
        super.onCreate(savedInstanceState);    
        setContentView(R.layout.first);

        ImageView imageViewCall = (ImageView) findViewById(R.id.ring_mig);

        imageViewCall.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v){
                try{
                    showDialog("0728570527");
                } catch (Exception e){
                    e.printStackTrace();
                }                   
            }    
        });    
    }

    public void showDialog(final String phone) throws Exception {
        AlertDialog.Builder builder = new AlertDialog.Builder(Firstclass.this);

        builder.setMessage("Ring: " + phone);       

        builder.setPositiveButton("Ring", new DialogInterface.OnClickListener(){
            @Override
            public void onClick(DialogInterface dialog, int which){

                Intent callIntent = new Intent(Intent.ACTION_DIAL);// (Intent.ACTION_CALL);                 
                callIntent.setData(Uri.parse("tel:" + phone));
                startActivity(callIntent);

                dialog.dismiss();
            }
        });

        builder.setNegativeButton("Abort", new DialogInterface.OnClickListener(){   
            @Override
            public void onClick(DialogInterface dialog, int which){
                dialog.dismiss();
            }
        });         
        builder.show();
    }    
}

回答by CrandellWS

Thanks nikki your answer has helped me improve an existing simply by adding my desired action as follows

谢谢nikki,你的回答帮助我改进了现有的,只需添加我想要的操作如下

AlertDialog.Builder builder = new AlertDialog.Builder(this);

builder.setTitle("Do this action");
builder.setMessage("do you want confirm this action?");

builder.setPositiveButton("YES", new DialogInterface.OnClickListener() {

    public void onClick(DialogInterface dialog, int which) {
        // Do do my action here

        dialog.dismiss();
    }

});

builder.setNegativeButton("NO", new DialogInterface.OnClickListener() {

    @Override
    public void onClick(DialogInterface dialog, int which) {
        // I do not need any action here you might
        dialog.dismiss();
    }
});

AlertDialog alert = builder.create();
alert.show();

回答by Warpzit

Steves answer is correct though outdated with fragments. Here is an example with FragmentDialog.

Steves 的回答是正确的,尽管已经过时了。这是 FragmentDialog 的示例。

The class:

班上:

public class SomeDialog extends DialogFragment {

    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {
        return new AlertDialog.Builder(getActivity())
            .setTitle("Title")
            .setMessage("Sure you wanna do this!")
            .setNegativeButton(android.R.string.no, new OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    // do nothing (will close dialog)
                }
            })
            .setPositiveButton(android.R.string.yes,  new OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    // do something
                }
            })
            .create();
    }
}

To start dialog:

开始对话:

            FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
            // Create and show the dialog.
            SomeDialog newFragment = new SomeDialog ();
            newFragment.show(ft, "dialog");

You could also let the class implement onClickListenerand use that instead of embedded listeners.

您还可以让类实现onClickListener和使用它而不是嵌入式侦听器。

回答by Cristan

In Kotlin:

在科特林:

AlertDialog.Builder(this)
    .setTitle(R.string.question_title)
    .setMessage(R.string.question_message)
    .setPositiveButton(android.R.string.yes) { _, _ -> yesClicked() }
    .setNegativeButton(android.R.string.no) { _, _ -> noClicked() }
    .show()

回答by Hitesh Sahu

Show dialog anonymously as chain of commands & without defining another object:

将对话框匿名显示为命令链 & 无需定义另一个对象:

 new AlertDialog.Builder(this).setTitle("Confirm Delete?")
                        .setMessage("Are you sure?")
                        .setPositiveButton("YES",
                                new DialogInterface.OnClickListener() {
                                    public void onClick(DialogInterface dialog, int which) {

                                       // Perform Action & Dismiss dialog                                 
                                        dialog.dismiss();
                                    }
                                })
                        .setNegativeButton("NO", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                // Do nothing
                                dialog.dismiss();
                            }
                        })
                        .create()
                        .show();

回答by javaxian

All the answers here boil down to lengthy and not reader-friendly code: just what the person asking was trying to avoid. To me, was the easiest approach is to employ lambdas here:

这里的所有答案都归结为冗长且不便于阅读的代码:正是提出问题的人试图避免的。对我来说,最简单的方法是在这里使用 lambdas:

new AlertDialog.Builder(this)
        .setTitle("Are you sure?")
        .setMessage("If you go back you will loose any changes.")
        .setPositiveButton("Yes", (dialog, which) -> {
            doSomething();
            dialog.dismiss();
        })
        .setNegativeButton("No", (dialog, which) -> dialog.dismiss())
        .show();

Lambdas in Android require the retrolambda plugin (https://github.com/evant/gradle-retrolambda), but it's hugely helpful in writing cleaner code anyways.

Android 中的 Lambda 需要 retrolambda 插件(https://github.com/evant/gradle-retrolambda),但无论如何它对编写更清晰的代码非常有帮助。