Reputation: 4269
So I looked at the code on developer.android.com According to them this is the way things to be done ...
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();
}
}
and I want the object of this class to be created when an item is clicked from the option menu ... But I don't know how to do that ???
Upvotes: 0
Views: 1399
Reputation: 94
MainActiviy:
//Displaying the dialog box
FragmentManager fragmentManager = getSupportFragmentManager();
FireMissilesDialogFragment fmdl = new FireMissilesDialogFragment(MainActivity.this);
fmdl.show(fragmentManager,"dialog");
Add this to your FireMissilesDialogFragment.java:
Context context;
public FireMissilesDialogFragment(Context context) {
this.context = context;
}
....
....
rest of the code
Upvotes: 1
Reputation: 86948
If I understand your question, you want a way to tell another class when the user clicks "Ok". A common approach is to create your own listener, the Developer's Guide has a great example of this.
The Basics
Create a callback:
public static class FragmentA extends ListFragment {
...
// Container Activity must implement this interface
public interface OnMyEventListener {
public void onMyEvent();
}
...
}
Set the callback:
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");
}
}
...
}
Call the callback:
.setPositiveButton(R.string.fire, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// FIRE ZE MISSILES!
mListener.onMyEvent();
}
})
Upvotes: 2