对话框不会显示

时间:2013-05-09 06:08:09

标签: java android

我创建了一个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();
}
}

2 个答案:

答案 0 :(得分:0)

尝试使用

FragmentTransaction ft = getSupportFragmentManager().beginTransaction();

答案 1 :(得分: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