Android onCreateDialog()中的AlertDialog.Builder工作不正常
我正在使用Android onCreateDialog()中的AlertDialog.Builder工作不正常,android,dialog,Android,Dialog,我正在使用DialogFragment(v4)实现一个带有ViewPager的对话框。除了我试图在对话框中添加标题、正按钮和负按钮外,一切都很好 以下是我所做的: @Override public Dialog onCreateDialog(Bundle savedInstanceState) { AlertDialog.Builder builder = new AlertDialog.Builder(getActivity()); builder.setTitle("修改时间
DialogFragment
(v4)实现一个带有ViewPager
的对话框。除了我试图在对话框中添加标题、正按钮和负按钮外,一切都很好
以下是我所做的:
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setTitle("修改时间...")
.setPositiveButton(R.string.dialog_setDatetime_positiveButton, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
}
})
.setNegativeButton(R.string.dialog_setDatetime_negativeButton, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
getDialog().dismiss();
}
});
AlertDialog dialog = builder.show();
return dialog;
}
(我认为汉字没有任何区别,所以请忽略它们。)
结果是,标题和按钮没有显示。似乎AlertDialog.Builder
工作不正常,或者我做错了什么
在运行棒棒糖的Nexus5上测试
编辑:如果我调用builder.create()
并返回对话框,我将得到错误消息:
android.util.AndroidRuntimeException:requestFeature()必须在添加内容之前调用
您需要调用builder.create(),然后返回对话框。您可以像下面那样使用它。(只需忽略汉字)
以下是我的作品:
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
return new AlertDialog.Builder(getActivity())
.setTitle("title")
.setPositiveButton("Positive button",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
//process the positive button click event
}
}
)
.setNegativeButton("Negative button",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
//process the negative button click event
}
}
)
.create();
}
如果调用builder.create(),将引发运行时异常。实际上,我首先使用了create(),遇到了这个问题,并通过调用show()找到了一个解决方案来避免它。如果我调用builder.create(),将引发运行时异常。无论如何,谢谢使用
builder.create().show()
到@Apurva:builder.create().show()
不会返回对话框。如何处理返回值?将getActivity()
替换为YourActivityName。这是new AlertDialog.Builder(getActivity())中的你应该试试齐尔麦克的答案
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
return new AlertDialog.Builder(getActivity())
.setTitle("title")
.setPositiveButton("Positive button",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
//process the positive button click event
}
}
)
.setNegativeButton("Negative button",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
//process the negative button click event
}
}
)
.create();
}