从另一个片段显示D​​ialogFragment

时间:2014-08-04 18:07:18

标签: android fragment dialogfragment

我设法从一个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我点击应用程序关闭之前的Back按钮我看到Dialog存在。所以看起来它显示在我的片段下面,或者只是以某种方式放在backStack上。我不知道。

我尝试通过侦听器从TestFragment向侦听侦听器的MainActivity发送事件,从Fragment或MainActivity中显示DialogFragment。

0 个答案:

没有答案