【问题标题】:Understanding Dynamic Fragment Loading了解动态片段加载
【发布时间】:2023-03-26 12:41:01
【问题描述】:

在 Android 教程中,在 Building a Flexible UI 下,示例中给出的 Fragment 实例化发生在 Activitiy 的 onCreate() 中,如下所示:

public void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);
    setContentView(R.layout.news_articles);

    // Check that the activity is using the layout version with
    // the fragment_container FrameLayout
    if (findViewById(R.id.fragment_container) != null) {

        ...

        getSupportFragmentManager().beginTransaction()
                .add(R.id.fragment_container, firstFragment).commit();
    }
}

不包括 if (findViewById(R.id.fragment_container) != null) 检查,我自己的示例在启动时失败:

IllegalStateException:指定的孩子已经有一个父母。您必须先在孩子的父母上调用 removeView()。

我的问题是:

if 检查有什么作用?我不明白教程示例中的注释解释。我的理解是,由于某种原因,onCreate() 在活动生命周期中被不止一次调用,但我不知道为什么?诚然,我对活动生命周期的了解很少。

【问题讨论】:

    标签: android dynamic android-fragments


    【解决方案1】:

    if 检查有什么作用?

    它检查容器是否存在。您不能将片段添加到不存在的容器中。

    【讨论】:

    • 但是为什么在这个单一活动、单一片段的应用程序中,onCreate() 会在容器存在之前被调用?即为什么 onCreate 首先被多次调用,应该发生的只是应用程序的主要活动被调用一次。
    • @Navonod:“但是为什么在这个单一活动、单一片段的应用程序中,onCreate() 在容器存在之前就被调用了?” ——它不是一个单片断的应用程序。这是-small-normal 设备上的单片段应用程序。本教程的上一步在-large-xlarge 设备上设置了多个静态片段。因此,并非所有setContentView() 调用都会使用此容器结束,因为会根据屏幕大小加载不同的布局。
    • @Navonod:“为什么 onCreate 一开始会被多次调用,应该发生的只是应用程序的主要活动被调用一次。” -- onCreate() 不仅会在最初创建活动时调用,而且会在配置更改时重新创建时调用。
    【解决方案2】:

    这是简单的Navonod,

    if (findViewById(R.id.**fragment_container**) != null) {
    
      getSupportFragmentManager().beginTransaction().add(R.id.**fragment_container**,firstFragment).commit();
    
    }
    

    在 res/layout/news_articles.xml:

    <FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:id="@+id/fragment_container"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />
    

    所以它已经在应用程序第一次调用主题时创建,这就是我们检查findViewById(R.id.fragment_container) != null的原因。但是,如果您在应用程序运行时动态删除它,此代码将确保您将其安全地返回到 Fragment 应该驻留的 FrameLayout 中。

    P.S:这里实际上没有两次调用 onCreate :)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-06-14
      • 1970-01-01
      • 1970-01-01
      • 2019-08-29
      • 2020-01-31
      相关资源
      最近更新 更多