0

所以我查看了 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();
}
}

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

4

2 回答 2

2

如果我理解您的问题,您想要一种在用户单击“确定”时告诉另一个班级的方法。一种常见的方法是创建自己的侦听器,开发人员指南有一个很好的例子



创建回调

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();
     }
})
于 2013-01-23T16:41:54.707 回答
1

主要活动:

//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
于 2019-07-09T04:51:51.323 回答