如何为Sherlock片段创建Dialog片段?

时间:2013-08-05 14:05:58

标签: android android-fragments actionbarsherlock android-alertdialog

在我的应用中,我正在使用ActionBArSherlock来创建片段。主要活动是 SherlockFragmentActivity ,我从中创建片段。片段在他们自己的类文件中,并扩展 SherlockFragment 。我需要在片段中显示警告对话框,但我无法这样做。

我用Google搜索了,但是徒劳无功。我检查了与ActionBarSherlock库一起提供的样本。他们已经展示了如何在FragmentActivity中创建对话框,而不是在Fragment中创建对话框。我尝试在片段中实现相同但我不能使用getSupportFragmentManager()。对于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();
    }
}

你能告诉我如何在Sherlock片段中显示一个对话框吗?

1 个答案:

答案 0 :(得分:4)

在SherlockFragment中,您可以致电

getSherlockActivity().getSupportFragmentManager();

让你的片段管理器显示对话框片段。