如何从扩展DialogFragment的类创建一个对话框?

时间:2013-01-23 16:28:09

标签: android dialog

所以我查看了developer.android.com上的代码 根据他们的说法,这就是要做的事情......

public class FireMissilesDialogFragment extends DialogFragment {
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
    // Use the Builder class for convenient dialog construction
    AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
    builder.setMessage(R.string.dialog_fire_missiles)
           .setPositiveButton(R.string.fire, new DialogInterface.OnClickListener() {
               public void onClick(DialogInterface dialog, int id) {
                   // FIRE ZE MISSILES!
               }
           })
           .setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
               public void onClick(DialogInterface dialog, int id) {
                   // User cancelled the dialog
               }
           });
    // Create the AlertDialog object and return it
    return builder.create();
}
}

我希望在从选项菜单中单击某个项目时创建此类的对象... 但我不知道怎么做???

2 个答案:

答案 0 :(得分:2)

如果我理解了您的问题,那么当用户点击“确定”时,您需要一种方法来告诉另一个班级。一种常见的方法是创建自己的监听器,开发人员指南有great example


基础知识
创建一个回调:

public static class FragmentA extends ListFragment {
    ...
    // Container Activity must implement this interface
    public interface OnMyEventListener {
        public void onMyEvent();
    }
    ...
}

设置回调:

public static class FragmentA extends ListFragment {
    OnMyEventListener mListener;
    ...
    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        try {
            mListener = (OnMyEventListener) activity;
        } catch (ClassCastException e) {
            throw new ClassCastException(activity.toString() + " must implement OnMyEventListener");
        }
    }
    ...
}

调用回调:

.setPositiveButton(R.string.fire, new DialogInterface.OnClickListener() {
     public void onClick(DialogInterface dialog, int id) {
         // FIRE ZE MISSILES!
         mListener.onMyEvent();
     }
})

答案 1 :(得分:0)

MainActiviy:

//Displaying the dialog box
FragmentManager fragmentManager = getSupportFragmentManager();
FireMissilesDialogFragment fmdl = new FireMissilesDialogFragment(MainActivity.this);
fmdl.show(fragmentManager,"dialog");

将此添加到FireMissilesDialogFragment.java:

Context context;
public FireMissilesDialogFragment(Context context) {
   this.context = context;
}
....
....
rest of the code