对话框不会显示
我创建了一个AlertDialogFragment类,我试图用下面的代码从另一个类中显示它,但我不断收到一个错误,将类型从FragmentTranscation更改为FragmentManager。如果我将其更改为FragmentManager,我得到一个消息更改为FragmentTranscation,每当我改变FragmentTranscation,我得到一个消息更改为FragmentManager:对话框不会显示
这里是展示alertDialog代码:
FragmentTransaction ft= getFragmentManager().beginTransaction();
AlertDialogFragment newFragment= new AlertDialogFragment();
newFragment.show(ft, "alertDialog");
下面是类代码:
public class AlertDialogFragment extends android.support.v4.app.DialogFragment {
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
AlertDialog.Builder builder
= new AlertDialog.Builder(getActivity());
builder.setMessage("Staying in Touch With The Ones You Love");
builder.setTitle("Togetherness");
builder.setCancelable(false);
builder.setPositiveButton("yes", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
}
});
builder.setNegativeButton("No", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
return builder.create();
}
}
要显示片段,您需要替换现有的片段或将新的片段添加到现有的视图。
编辑:对不起,没有注意到它是一个对话框片段。 使用此:
// DialogFragment.show() will take care of adding the fragment
// in a transaction. We also want to remove any currently showing
// dialog, so make our own transaction and take care of that here.
FragmentTransaction ft = getFragmentManager().beginTransaction();
Fragment prev = getFragmentManager().findFragmentByTag("alertDialog");
if (prev != null) {
ft.remove(prev);
}
ft.addToBackStack(null);
// Create and show the dialog.
newFragment.show(ft, "alertDialog");
这里看看例子:http://developer.android.com/reference/android/app/DialogFragment.html
记住如果你使用的是老式API级别片段API等级11介绍,按照说明这里使用支持库的所有片段的东西(我看你DialogFragment
已经从支持库FragmentDialog
继承)
http://developer.android.com/training/basics/fragments/support-lib.html
非常感谢。这工作完美! – user2348040 2013-05-10 00:36:05
这正是我所期待的。 – user2348040 2013-05-10 00:41:30
尝试使用
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
非常感谢。这工作完美! – user2348040 2013-05-10 00:34:54
请将此标记为准确答案:) – Neoh 2013-05-10 13:53:47
检查本教程 - > http://vinaygopinath.wordpress.com/2012/11/10/alertdialog-using-fragment/ – 2013-05-09 06:59:58