单击按钮时如何打开对话框? [英] How to open a dialog when I click a button?

查看:114
本文介绍了单击按钮时如何打开对话框?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个按钮,按下后想打开一个对话框.这是我的代码:

I have a button and I would like to open a dialog when pressed. This is my code:

Button more = (Button) findViewById(R.id.more);
more.setOnClickListener(new View.OnClickListener() {
    public void onClick(View view) {
        //Intent myIntent = new Intent(view.getContext(), agones.class);
        //startActivityForResult(myIntent, 0);

        AlertDialog alertDialog = new AlertDialog.Builder(this).create();
        alertDialog.setTitle("hi");
        alertDialog.setMessage("this is my app");

        alertDialog.setButton("Continue..", new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int which) {
            // here you can add functions
        }
        });
    }
});

推荐答案

正如@Roflcoptr所说,您尚未调用 alertDialog.show()方法.因此您的对话框不会出现.

As @Roflcoptr has said, you haven't called alertDialog.show() method. thus your dialog doesn't appear.

这是您编辑的代码:

Button more = (Button) findViewById(R.id.more);
more.setOnClickListener(new View.OnClickListener() {
    public void onClick(View view) {
        //Intent myIntent = new Intent(view.getContext(), agones.class);
        //startActivityForResult(myIntent, 0);


        AlertDialog alertDialog = new AlertDialog.Builder(<YourActivityName>this).create(); //Read Update
        alertDialog.setTitle("hi");
        alertDialog.setMessage("this is my app");

        alertDialog.setButton("Continue..", new DialogInterface.OnClickListener() {
           public void onClick(DialogInterface dialog, int which) {
              // here you can add functions
           }
        });

        alertDialog.show();  //<-- See This!
    }

});

如果您写的是 this 而不是< ActivityName> .this ,则它将引用 View.OnClickListener ,因为当前正在其中访问 this .您需要在此处输入活动"的名称.

if you write this instead of <ActivityName>.this, then it is going to take the reference of View.OnClickListener since this is currently being accessed inside it. You need to give your Activity's name there.

这篇关于单击按钮时如何打开对话框?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆