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

Sol*_*olo 345 android android-alertdialog

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

我曾经是一名.NET开发人员,我想知道是否有以下的Android相当于?

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

Ste*_*ley 720

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();
Run Code Online (Sandbox Code Playgroud)

你也可以重用它,DialogInterface.OnClickListener如果你有其他是/否的盒子应该做同样的事情.

如果您要在a中创建Dialog View.OnClickListener,则可以使用它view.getContext()来获取Context.或者你可以使用yourFragmentName.getActivity().

  • 我自己,我已经使用了很多次.但我发现在SO上查找它实际上更容易,更快捷.这里给出的代码示例非常简单......我真的希望Android文档看起来像这样. (9认同)
  • @EricLeschinski可能"this"不是一个上下文,试试这个:`AlertDialog.Builder builder = new AlertDialog.Builder(getView().getContext());` (4认同)
  • 新的AlertDialog.Builder(这); 编译时错误:'构造函数AlertDialog.Builder(new View.OnClickListener(){})未定义' (3认同)
  • 用户点击"是"或"否"按钮后,简单实用的btw对话框将自动解除.你无需做任何事情. (3认同)

nik*_*kki 153

试试这个:

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();
Run Code Online (Sandbox Code Playgroud)

  • 就个人而言,我更喜欢那段代码片段而不是接受的答案 (25认同)
  • @nikki 为什么两者都有dismiss() ? (2认同)

Eri*_*ass 32

史蒂夫H的答案很明显,但这里有更多的信息:对话框的工作原理是因为Android中的对话是异步的(在显示对话框时执行不会停止).因此,您必须使用回调来处理用户的选择.

查看这个问题,以便更长时间地讨论Android和.NET之间的差异(因为它与对话框有关): Dialogs/AlertDialogs:如何在对话框启动时"阻止执行"(.NET风格)

  • 谢谢,Android对话框是异步的这一事实使得一切都清晰(合理).似乎我在为Android开发应用程序时需要"思考.Net":) (8认同)

has*_*ash 14

这对我有用:

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();
Run Code Online (Sandbox Code Playgroud)


Chr*_*ian 8

Kotlin 实现。

您可以创建一个像这样的简单函数:

fun dialogYesOrNo(
        activity: Activity,
        title: String,
        message: String,
        listener: DialogInterface.OnClickListener
    ) {
        val builder = AlertDialog.Builder(activity)
        builder.setPositiveButton("Yes", DialogInterface.OnClickListener { dialog, id ->
            dialog.dismiss()
            listener.onClick(dialog, id)
        })
        builder.setNegativeButton("No", null)
        val alert = builder.create()
        alert.setTitle(title)
        alert.setMessage(message)
        alert.show()
    }
Run Code Online (Sandbox Code Playgroud)

并这样称呼它:

dialogYesOrNo(
  this,
  "Question",
  "Would you like to eat?",
  DialogInterface.OnClickListener { dialog, id ->
    // do whatever you need to do when user presses "Yes"
  }
})
Run Code Online (Sandbox Code Playgroud)


Hit*_*ahu 7

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

 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();
Run Code Online (Sandbox Code Playgroud)


Xar*_*mer 6

询问某人是否要呼叫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();
    }    
}
Run Code Online (Sandbox Code Playgroud)


jav*_*ian 6

这里的所有答案都归结为冗长且不适合读者的代码:这正是提问者试图避免的。对我来说,最简单的方法是在这里使用 lambda:

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();
Run Code Online (Sandbox Code Playgroud)

Android 中的 Lambda 需要 Retrolambda 插件 ( https://github.com/evant/gradle-retrolambda ),但它对于编写更简洁的代码非常有帮助。


Cra*_*lWS 5

谢谢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();
Run Code Online (Sandbox Code Playgroud)


War*_*zit 5

史蒂夫的答案是正确的,尽管已经过时了。这是FragmentDialog的示例。

班级:

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();
    }
}
Run Code Online (Sandbox Code Playgroud)

要启动对话框:

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

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

  • 我的建议是:如果不仅需要重用布局,还需要背景和生命周期代码,请使用“片段”对话框。使用该片段,您可以进行相关的活动生命周期控制,并且可以对诸如create(在用户旋转设备时重新创建UI),暂停,继续等事件做出反应。简而言之,是一个包含一些精心设计的UI的对话框。如果您不需要它,并且对话框非常简单,则常规对话框可以正常工作。 (2认同)

Cri*_*tan 5

在科特林:

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()
Run Code Online (Sandbox Code Playgroud)