我有一个问题,我需要在 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>
我想要的是用我的 fragment 替换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();
最佳答案
通常你直接使用DialogFragment哪个名字是 self 解释的。
这是我的代码示例,其中包含一个 int
作为 arg 发送。
基本上,您创建了一个 DialogFragment
,它扩展了 DialogFragment
。
您必须编写 newInstance
和 onCreateDialog
方法。
然后在调用 fragment 中创建该 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;
}
}
调用对话框 fragment 是通过执行此操作从另一个 fragment 完成的。
请注意,值 0
是我发送的 int。
YourDialogFragment yourDialogFragment = YourDialogFragment.newInstance(0);
YourDialogFragment.show(getFragmentManager().beginTransaction(), "DialogFragment");
在您的情况下,如果您不需要传递任何内容,请删除 DialogFragment 中的相应行,并且不要在 YourDialogFragment.newInstance()
编辑/关注
不确定是否真正理解您的问题。 如果您只需要用另一个 fragment 替换一个 fragment ,您可以使用
getFragmentManager().beginTransaction().replace(R.id.your_fragment_container, new YourFragment()).commit();
关于对话框内的android fragment ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20214073/