[英]AlertDialog to pop up on button click
我有一个TableLayout,希望用户可以在运行时为其添加项目(并使用单个EditText命名这些项目)。 因此,我需要一个“添加”按钮,我认为它适用于AlertDialog。 从android开发人员教程中获取标准代码:
AlertDialog.Builder builder = new AlertDialog.Builder(this);
LayoutInflater inflater = this.getLayoutInflater();
builder.setView(inflater.inflate(R.layout.add_layout,null));
builder.setPositiveButton(R.string.yes, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// User clicked OK button
}
});
builder.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// User cancelled the dialog
}
});
AlertDialog dialog = builder.create();
dialog.show();
当将其放入Activity的onCreate方法中时,而不是将其插入此“添加”按钮的onClick方法中时,该方法非常有效。 为什么会这样,我该如何解决呢? 更多信息:通过活动的XML文件android:onClick =“ Add”调用Add-buttons onClick方法,该文件随后是活动的java / class文件中的函数。 单击“添加”按钮时发生的只是活动崩溃,而不是整个应用程序崩溃,并且我向父活动返回了一步,并显示以下消息:“不幸的是,应用程序已停止”。
我认为您可能尚未对此问题做出太多回应,因为您没有提供足够的信息。 您说将AlertDialog放入“添加”按钮的onClick方法时不起作用 。 怎么了? 应用会崩溃吗? 如果是这样,您会得到什么错误消息? 还是不会崩溃,但不会显示AlertDialog? 您如何将AlertDialog放在onClick方法中? 您是在布局xml中使用android:onClick="someMethod"
属性,还是在代码中分配onClickListener?
我猜一下,并假设您正在以类似以下形式的代码在代码中分配onClickListener:
myAddButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
LayoutInflater inflater = this.getLayoutInflater();
builder.setView(inflater.inflate(R.layout.add_layout,null));
...
}
});
如果您采用上述方法,则需要意识到您正在使用匿名内部类,并且this
关键字引用了它所在的对象。在匿名内部类中, this
关键字不再引用父活动。匿名内部类已被放入。
AlertDialog.Builder()
构造函数希望您为其传递上下文。 当您在Activity的onCreate()方法中编写AlertDialog.Builder(this)
时, this
是指Activity,而Activity是Context的子类,因此AlertDialog.Builder()
构造函数很高兴。
但是,当您在AlertDialog.Builder(this)
中编写AlertDialog.Builder(this)
时, this
现在引用的是View.OnClickListener()
,它不是Context的子类,因此AlertDialog.Builder()
构造函数不满意。
如果这不是您要采用的方法, 请提供更多信息,以便为您提供帮助。
如果您采用的是这种方法,则可以通过将AlertDialog创建放回Activity中来解决问题。
...
myAddButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
showMyAlertDialog(); // Call a method in your Activity
}
});
...
// Create a method in your activity
private void showMyAlertDialog() {
AlertDialog.Builder builder = new AlertDialog.Builder(this); // <-- 'this' now refers to the Activity
LayoutInflater inflater = this.getLayoutInflater();
builder.setView(inflater.inflate(R.layout.add_layout,null));
...
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.