1

我已经设法从 Activity 中显示 DialogFragment。但是如何从 Fragment 实现这一点呢?

我的 DialogFragment 看起来像这样:

package com.tes

import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;

public class AlertDialogFragment extends DialogFragment
{

    public AlertDialogFragment()
    {
        super();
    }

    public static AlertDialogFragment newInstance()
    {
        return new AlertDialogFragment();
    }


    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
    }

    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {
        AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(getActivity());
        alertDialogBuilder.setTitle("Test title");
        alertDialogBuilder.setMessage("Are you sure?");
        alertDialogBuilder.setPositiveButton("OK",  new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                // on success
            }
        });
        alertDialogBuilder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        });

        return alertDialogBuilder.create();
    }
}

我有一个主要活动显示 TestFragment 像这样:

FragmentManager fragmentManager = getSupportFragmentManager();
        FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
        fragmentTransaction.addToBackStack(fragmentTag);
        fragmentTransaction.replace(R.id.container,  fragment)
                .commit();

在我的 TestFragment 中,我想显示我的对话框:

 AlertDialogFragment newFragment = AlertDialogFragment
                .newInstance();

        FragmentManager fm = getSupportFragmentManager();
        newFragment.show(fm, "dialogs");

但它不起作用。Wjen 我点击后退按钮,在应用程序关闭之前我看到对话框存在。所以看起来它显示在我的片段下方,或者只是以某种方式放在 backStack 上。我不知道。

我试图通过从 TestFragment 到 MainActivity 的监听器发送事件来从 Fragment 或 MainActivity 显示 DialogFragment,该 MainActivity 监听监听器。

4

0 回答 0