In my app I'm using ActionBArSherlock to create fragments. The main activity is a SherlockFragmentActivity from where I create the fragments. The fragments are in their own class files and they extend SherlockFragment. I need to display an alert dialog in a fragment but I'm unable to do so.
I googled it, but in vain. I checked the samples given along with the ActionBarSherlock library. They have shown how to create a dialog in a FragmentActivity but not in a Fragment. I tried implementing the same in a fragment but I can't use getSupportFragmentManager()
. It is undefined for the type Fragment.
public class Fragment1 extends SherlockFragment {
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
rootView = inflater.inflate(R.layout.fragment2, container, false);
return rootView;
}
public void someFunction(){
if(somethingHappens)
showDialog();
}
//the code that follows is from the sample in ActionBarSherlock
void showDialog() {
DialogFragment newFragment = MyAlertDialogFragment.newInstance(
R.string.alert_dialog_two_buttons_title);
newFragment.show(getSupportFragmentManager(), "dialog"); //getSupportFragmentManager() is undefined for the type Fragment
}
public void doPositiveClick() {
// Do stuff here.
Log.i("FragmentAlertDialog", "Positive click!");
}
public void doNegativeClick() {
// Do stuff here.
Log.i("FragmentAlertDialog", "Negative click!");
}
public static class MyAlertDialogFragment extends SherlockDialogFragment {
public static MyAlertDialogFragment newInstance(int title) {
MyAlertDialogFragment frag = new MyAlertDialogFragment();
Bundle args = new Bundle();
args.putInt("title", title);
frag.setArguments(args);
return frag;
}
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
int title = getArguments().getInt("title");
return new AlertDialog.Builder(getActivity())
.setIcon(R.drawable.alert_dialog_icon)
.setTitle(title)
.setPositiveButton(R.string.alert_dialog_ok,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
((FragmentAlertDialogSupport)getActivity()).doPositiveClick(); // Cannot cast from FragmentActivity to fragment
}
}
)
.setNegativeButton(R.string.alert_dialog_cancel,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
((FragmentAlertDialogSupport)getActivity()).doNegativeClick(); //Cannot cast from FragmentActivity to fragment
}
}
)
.create();
}
}
Can you tell me how to show a dialog in a Sherlock Fragment?
From within a SherlockFragment you may call
getSherlockActivity().getSupportFragmentManager();
to get your fragment manager to show the dialog fragment.