首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >onClick()和AlertDialog onClick - Android

onClick()和AlertDialog onClick - Android
EN

Stack Overflow用户
提问于 2017-03-30 09:09:05
回答 1查看 1.2K关注 0票数 0

我是一个使用Android的新程序员,在我的活动代码中有以下内容:

代码语言:javascript
复制
@Override
protected void onCreate(Bundle savedInstanceState) { /* code */ }

@Override
public void onClick(View ButtonSelected) 
{ 
   switch (ButtonSelected.getId())
   {
      case R.id.Button1:
      // code
      break;

      case R.id.Button2:
      // code
      break;

   }
}

public void GUIMessageBox()
{
    /* this function is called in the cases where a message box must appear
       to the user and he has to select either "Yes" or "No".
       the function initializes the AlertDialog.Builder and present it to the
       user*/

     new AlertDialog.Builder(this)
            .setTitle("Sample Title")
            .setMessage("Sample Message")
            .setPositiveButton("Yes", new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int id) {
            // code for Yes selection
        }
    })
            .setNegativeButton("No", new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int id) {
            // code for No selection
        }
    })
            .show();
}

当我运行应用程序时,应用程序正常工作。当需要显示消息框时,我得到错误“不幸的是,应用程序停止了”

当我回到我的代码时,.setPositiveButton和.setNegativeButton看起来如下:

代码语言:javascript
复制
  .setPositiveButton("Yes", (arg0, arg1) -> {

                        // code for "Yes" case
                })

.setNegativeButton( "No“,(arg0,arg1) -> { //用于”否“的代码)

})

我认为这是因为有多个"onClick“函数。我试图避免这一点,但仍然没有设法解决它。

有人对此有什么提示吗?

谢谢您:)

EN

回答 1

Stack Overflow用户

发布于 2017-03-30 09:16:43

中更改“此”

新AlertDialog.Builder(此)

到"nameClass.this“(前。( MainActivity.this)并在两者中更改"id“。

公共无效onClick(DialogInterface对话框,int id)

转到“哪个”

代码语言:javascript
复制
public void GUIMessageBox()
{
    /* this function is called in the cases where a message box must appear
       to the user and he has to select either "Yes" or "No".
       the function initializes the AlertDialog.Builder and present it to the
       user*/

     new AlertDialog.Builder(this)
            .setTitle("Sample Title")
            .setMessage("Sample Message")
            .setPositiveButton("Yes", new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int id) {
            // code for Yes selection
        }
    })
            .setNegativeButton("No", new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int id) {
            // code for No selection
        }
    })
            .show();
}

这就是我把它写在代码中的方式,希望它能工作

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

https://stackoverflow.com/questions/43113288

复制
相关文章

相似问题

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