android - 如何将 fragment 添加到 DialogFragment 的布局中?

标签 android android-layout android-fragments android-dialogfragment fragmenttransaction

我有一个自定义 DialogFragment,它包含一个布局、一些 UI 元素和一个 Fragment holder 布局。我需要做的是将 Content fragment 膨胀到 holder 布局中,并在其中提供导航。单击添加的 fragment 内的按钮, View 将导航到另一个 View 。该 fragment 将被同一容器中的另一个 fragment 替换,即 contentFragment1 将显示一些数据,单击预览按钮时,contentFragment1 将替换为 contentFragment2。 我在某处读到,您不能将硬编码到 xml 的 fragment 替换为另一个 fragment 。 因此,我试图将 contentFragment1 添加到对话框 fragment 的 onActivityCreated() 中的 viewholder。但是我收到一个错误,指出未找到 R.id.fragmentHolder 指向的资源。可能的原因是什么?

这是我的 DialogFragment 代码:

public class MyDialog extends DialogFragment {
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
    Dialog customDialog = new Dialog(getActivity());
    customDialog.getWindow().requestFeature(Window.FEATURE_NO_TITLE);
    customDialog.setContentView(R.layout.reports_dialog);
    return customDialog;
}

@Override
public void onActivityCreated(Bundle savedInstanceState) {
    android.app.FragmentTransaction fragmentTransaction =getFragmentManager().beginTransaction();
    fragmentTransaction.add(R.id.myFragmentHolder, new ReportsListFragment());
    fragmentTransaction.commit();
    super.onActivityCreated(savedInstanceState);
}

enter image description here

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="400dp"
    android:background="@android:color/transparent" >


    <TextView
        android:id="@+id/textView1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:text="This is my header text view for the Dialog"
        android:textSize="18sp" />

<RelativeLayout
    android:id="@+id/myFragmentHolder"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_below="@+id/headerlayout" >

</RelativeLayout>

最佳答案

经过多次尝试,我得出的结论是onCreateDialog() 没有 View ,它只是在调用setView() 时设置 View 。

这就是为什么在 dialogfragment 的布局中添加动态(framelayout 标记)或静态 fragment ( fragment 标记)会出现无父 View 重复 ID 错误。

要实现上述目标,应该使用带有可以动态膨胀的 framelayout 标签的 onCreateView。然后将标题和警报按钮添加到布局中。

关于android - 如何将 fragment 添加到 DialogFragment 的布局中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21258228/

相关文章:

java - 如何处理 Android 上的应用程序从免费版本升级到付费版本

Android开发最佳实践

android - 图像的 imageButton 边框

android - 约束布局 : change constraints programmatically

android - 如果文本比 View 长,动态 TextView 不会选取框

android - 如何在同一 Activity 中的 fragment 之间传递 gson JsonObject

Android DatePicker 监听器未触发

android - 如何使用自定义布局作为 RadioButton 标签

android - 如何在 Android 中为 fragment 制作单独的返回堆栈

android - 屏幕旋转 fragment