0

我创建了一个 AlertDialogFragment 类,并尝试使用以下代码从另一个类中显示它,但是将类型从 FragmentTranscation 更改为 FragmentManager 时不断收到错误消息。如果我将其更改为 FragmentManager,我会收到一条更改为 FragmentTranscation 的消息,每当我更改为 FragmentTranscation 时,我都会收到一条更改为 FragmentManager 的消息:

这是显示警报对话框的代码:

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();
}
}
4

2 回答 2

0

尝试使用

FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
于 2013-05-09T06:13:04.230 回答
0

要显示片段,您需要替换现有片段或将新片段添加到现有视图。

编辑:对不起,没有注意到它是一个对话框片段。用这个:

// 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 级别 11 中引入的。如果您使用的是较旧的 API 级别,请按照此处的说明将支持库用于所有片段内容(我看到您DialogFragment已经从支持库继承FragmentDialog

http://developer.android.com/training/basics/fragments/support-lib.html

于 2013-05-09T06:14:38.770 回答