我是使用Android工作室的新程序员,我在我的一个活动代码中有以下内容:
@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();
}
当我运行应用程序时,该应用程序正常工作。当需要显示消息框时,我收到错误“不幸的是,App已停止”
当我回到我的代码时,.setPositiveButton和.setNegativeButton看起来像:
.setPositiveButton("Yes", (arg0, arg1) -> {
// code for "Yes" case
})
.setNegativeButton(“No”,(arg0,arg1) - > { //“无”案例的代码
})
我认为是因为有多个“onClick”功能。 我试图避免这种情况,但仍未设法修复它。
有没有人提示这个?
谢谢:)
答案 0 :(得分:0)
在
中更改“this”new AlertDialog.Builder(this)
到“nameClass.this”(例如MainActivity.this)并更改两者中的“id”
public void onClick(DialogInterface对话框,int id)
到“哪个”
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();
}
我的代码就是这样,希望它有效