安卓内部对话框中的碎片

11

我有一个问题,需要在 android.app.Dialog 中显示一个 fragment

这是XML代码:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <FrameLayout
        android:id="@+id/marchecharts"
        android:layout_width="match_parent"
        android:layout_height="match_parent" >
    </FrameLayout>

</LinearLayout>
我想要的是用我的片段替换 marchecharts,有人能帮忙吗?
谢谢。
Dialog dialog = new Dialog(getActivity());
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog.setContentView(R.layout.marche_charts_parent);


//this is the part I think I need
Fragment fragment = new MarcheChartsFragment();
FragmentTransaction ft = ((FragmentActivity) dialog.getOwnerActivity()).getFragmentManager().beginTransaction();
ft.replace(R.id.marchecharts, fragment);  
ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
ft.addToBackStack(null);
ft.commit();

dialog.setCanceledOnTouchOutside(true);
dialog.getWindow().setLayout(ViewGroup.LayoutParams.FILL_PARENT, ViewGroup.LayoutParams.FILL_PARENT);
dialog.show();
1个回答

14

通常直接使用名称自解释的 DialogFragment

以下是我的示例代码,将 int 作为参数传递。

因此,基本上您需要创建一个扩展了 DialogFragmentDialogFragment。 您需要编写 newInstanceonCreateDialog 方法。 然后在调用 fragment 中创建该片段的新实例。

public class YourDialogFragment extends DialogFragment {
    public static YourDialogFragment newInstance(int myIndex) {
        YourDialogFragment yourDialogFragment = new YourDialogFragment();

        //example of passing args
        Bundle args = new Bundle();
        args.putInt("anIntToSend", myIndex);
        yourDialogFragment.setArguments(args);

        return yourDialogFragment;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        //read the int from args
        int myInteger = getArguments().getInt("anIntToSend");

        View view = inflater.inflate(R.layout.your_layout, null);

        //here read the different parts of your layout i.e :
        //tv = (TextView) view.findViewById(R.id.yourTextView);
        //tv.setText("some text")

        return view;
    }
}

从另一个片段调用对话框片段可以通过执行以下操作完成。 请注意,值0是我发送的整数。

YourDialogFragment yourDialogFragment = YourDialogFragment.newInstance(0);
YourDialogFragment.show(getFragmentManager().beginTransaction(), "DialogFragment");

如果您不需要传递任何东西,可以在 DialogFragment 中删除相应的行,并且在 YourDialogFragment.newInstance() 中不传递任何值。

编辑/跟进

不确定是否真正理解您的问题。 如果您只需将一个片段替换为另一个片段,则使用

getFragmentManager().beginTransaction().replace(R.id.your_fragment_container, new YourFragment()).commit();

感谢您的回复!我在onCreateDialog中遇到了一个错误:类型不匹配:无法将View转换为Dialog,出现在“return view”行。 - TootsieRockNRoll
2
重新考虑一下,我认为这并不能解决问题,因为我已经有一个片段了,我只需要在对话框中显示它。 - TootsieRockNRoll
据我理解你的问题,你想在对话框中显示自己的片段。如果这是你的问题,我提供的代码可以解决这个问题。 - HpTerm
谢谢你,基本上给了我一个提示,我有一个片段需要在手机上显示为普通片段,但在平板电脑上显示为对话框,所以我最终从DialogFragment扩展了自己的片段,目前效果很好。 - TootsieRockNRoll

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接