【问题标题】:Where is the ViewGroup container initialized?ViewGroup 容器在哪里初始化?
【发布时间】:2016-03-28 23:28:29
【问题描述】:

我正在尝试理解以下片段代码:

public class FragmentA extends Fragment { 
    public FragmentA(){
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
                  if(container!=null)
                      // WHY IS THIS CODE EXECUTED? I did not set container variable


          // why if I pass null insted of Container, I get the same result?
        return inflater.inflate(R.layout.fragment_a,container,false);
    }
}

这个 ViewGroup 容器我从未初始化过什么的。如果我从未初始化它,android 怎么知道我的容器是什么?

我不清楚的另一件事是当我调用 inflate 时,如果我将容器写为 null,结果是相同的。

return inflater.inflate(R.layout.fragment_a,null,false);

我在主要活动中使用 ViewPager。

我在 FragmentPagerAdapter 中创建的片段是这样的:

Fragment fragment = new FragmentA();

这些是我的 xml 文件:

<android.support.v4.view.ViewPager xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/pager"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity"/>

对于片段:

<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:background="#FFCC00" >

    <!-- TODO: Update blank fragment layout -->

    <TextView
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:layout_gravity="center"
        android:gravity="center"
          android:textColor="#ffffff"
        android:textStyle="bold"
        android:text="THIS IS FRAGMENT A" />

</FrameLayout>

编辑: 我在开发者网站上找到了这个:

传递给onCreateView()的容器参数是父容器 ViewGroup(来自活动的布局)您的片段布局 将被插入。 savedInstanceState 参数是一个 Bundle 提供有关片段的前一个实例的数据,如果 片段正在恢复(恢复状态在 关于处理片段生命周期的部分)。

但是,我仍然不清楚。我没有在 Fragment 调用中将任何 ViewGroup 传递给 Fragment....

【问题讨论】:

标签: android android-fragments view


【解决方案1】:

容器由片段外部提供。它要么在您在 xml 中使用 &lt;fragment&gt; 标记时自动生成,要么在您在代码中初始化片段时作为 FragmentTransaction 的一部分传递。

【讨论】:

  • 我编辑了答案,所以更清楚我的情况是什么
猜你喜欢
  • 1970-01-01
  • 2014-04-27
  • 2015-06-27
  • 1970-01-01
  • 1970-01-01
  • 2023-02-04
  • 1970-01-01
  • 1970-01-01
  • 2021-06-25
相关资源
最近更新 更多