android - 以编程方式将 fragment 添加到 LinearLayout

标签 android android-layout android-fragments

我正在尝试将嵌套的子 fragment 添加到父 fragment 中。

一切正常,但是......

起初我的代码:

public class FragmentDatasheetWithHeader extends Fragment {
   private long   mRowId;
   private String mSid;

   @Override
   public View onCreateView(final LayoutInflater inflater, final ViewGroup container, final Bundle savedInstanceState) {

      final ScrollView scrollView = new ScrollView(getActivity());
      final LinearLayout linearLayout = new LinearLayout(getActivity());
      linearLayout.setId(4711);
      linearLayout.setOrientation(LinearLayout.VERTICAL);

      scrollView.addView(linearLayout);

      createUI();

      return scrollView;
   }

   private void createUI() {

      final FragmentProductDetailHeader fragmentHeader = FragmentProductDetailHeader.newInstance(this.mRowId, FragmentProductDetailHeader.HEADERTYPE_SMALL);
      final FragmentDatasheet fragmentDatasheet = FragmentDatasheet.newInstance(this.mRowId, this.mSid);

      final FragmentManager fragmentManager = getChildFragmentManager();
      fragmentManager.beginTransaction().add(4711, fragmentHeader, "fragmentHeader").commit();
      fragmentManager.beginTransaction().add(4711, fragmentDatasheet, "fragmentDatasheet").commit();
   }
}

现在我的问题:

在开发人员选项中,我激活了“不保留 Activity (用户离开后立即销毁所有 Activity )”

当带有 FragmentDatasheetWithHeader 的 Activity 打开并且应用程序进入后台并返回前台时,嵌套的 fragment 会加倍。但它仅在嵌套 Fragment 的容器为 LinearLayout 时出现。如果容器是 FrameLayout,则嵌套的 fragment 不会加倍。

出了什么问题?

最佳答案

If the container is a FrameLayout the nested Fragments are not doubled.

这可能不是真的。更有可能的是,新 fragment 只是位于旧 fragment 之上,有效地掩盖了它们。因此,潜在的问题可能是相同的,视觉效果只是因为各种 ViewGroup 实现如何安排它们的 child 而不同。

也就是说,有一种简单的方法可以判断您的 fragment 是新“创建”的,还是从以前的状态“恢复”的:通过查看传入的 Bundle savedInstanceState 参数到 onCreateView()(以及其他各种与生命周期相关的方法,如 onActivityCreate() 等)。

更具体地说,您可能希望将类似这样的内容添加到 onCreateView():

if (savedInstanceState == null) createUI();

这样,只有在没有以前的状态可以恢复时,才会添加 fragment 。如果存在以前的状态,则框架应该改为恢复旧 fragment 。在后一种情况下,您可以通过按标签查找恢复的 fragment 来获取它们的句柄。

关于android - 以编程方式将 fragment 添加到 LinearLayout,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18542897/

相关文章:

android - 使用波纹效果更改 FAB 颜色

安卓接口(interface)

java - SlidingUpPanel 崩溃

android - 如何从下载的 apk 中实现应用程序 self 更新?

android - 如何将我的 dialogFragment 显示为圆角?

android - 如何在Android中的TextLayoutInput中的EditText下显示错误消息?

java - android片段中的Volley请求队列,不在 TextView 中设置json数组数据

Android Paging 3 库 PagingSource 失效,刷新键错误导致列表跳转(不使用房间)

android - 查找 NavHostFragment Jetpack Navigation Android 时出错

android - 如何将布局正确分配给特定的移动尺寸