首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何在单击按钮时打开对话框?

如何在单击按钮时打开对话框?
EN

Stack Overflow用户
提问于 2011-01-31 19:47:36
回答 4查看 93.3K关注 0票数 23

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

代码语言:javascript
复制
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
        }
        });
    }
});
EN

回答 4

Stack Overflow用户

回答已采纳

发布于 2011-01-31 19:52:42

正如@Roflcoptr所说,您还没有调用alertDialog.show()方法。这样你的对话框就不会出现了。

这是你编辑过的代码:

代码语言:javascript
复制
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当前正在它内部被访问。您需要在那里提供您的活动的名称。

票数 42
EN

Stack Overflow用户

发布于 2011-01-31 19:50:13

您的对话框不会显示,因为您没有调用AlertDialog#show

票数 11
EN

Stack Overflow用户

发布于 2020-06-14 18:58:12

Aman Alam's souliton是好的,但是.setButton()部分给了我一个错误。所以我用kotlin实现了它,并修复了这个错误。

Kotlin

代码语言:javascript
复制
    val dialog = AlertDialog.Builder(this)

    dialog.setTitle("Title")
          .setMessage("Write your message here.")
          .setPositiveButton("YES") { dialog, whichButton ->
               // DO YOUR STAFF
          }
         .setNegativeButton("NO") { dialog, whichButton ->
               // DO YOUR STAFF 
               // dialog.close()
          }

    dialog.show()

有关对话框的更多信息:https://developer.android.com/guide/topics/ui/dialogs

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/4850493

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档