1

在我的应用程序中,我使用 ActionBArSherlock 创建片段。主要活动是我创建片段的SherlockFragmentActivity。这些片段位于它们自己的类文件中,并且它们扩展了SherlockFragment。我需要在片段中显示警报对话框,但我无法这样做。

我用谷歌搜索了它,但徒劳无功。我检查了随 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();
    }
}

你能告诉我如何在夏洛克片段中显示对话吗?

4

1 回答 1

4

您可以从 SherlockFragment 中调用

getSherlockActivity().getSupportFragmentManager();

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

于 2013-08-05T14:15:03.767 回答