如何在Android中将Activity的根视图设置为片段?

时间:2015-04-07 17:12:27

标签: android android-fragments android-activity

我有一个片段,我想将整个片段设置为我的活动的根视图。我准备好了一切,并且我以编程方式实例化我的片段。我尝试过(在我的活动中):

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    FeedFragment fragment = [...];
    setContentView(fragment.getView());
}

但是我有一个空指针异常。换句话说,我怎样才能让我的片段像活动一样?我只针对ICS +,如果它有任何不同,我不需要支持旧版本。

3 个答案:

答案 0 :(得分:2)

试试这个

@Override
  public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
    View rootView = inflater.inflate(R.layout.all_lecturer_frag, container, false);

     ......

    return rootView;
   }

答案 1 :(得分:1)

@Override
protected void onCreate(Bundle savedInstanceState) 
{
super.onCreate(savedInstanceState);
  setContentView(R.layout.xxx);
  //initializations...    
    if (savedInstanceState == null) {
        // During initial setup, plug in the fragment.
        YourFragment details = new YourFragment();
        getFragmentManager().beginTransaction().add(R.id.your_root_frame_layout, details).commit();
    }
}

答案 2 :(得分:1)

根据设计,片段旨在帮助您重用屏幕空间,因此,片段必须存在于容器内。因此,虽然片段在技术上不能是根视图,但您可以将片段作为Activity内的唯一视图。为此,您应该在片段的onCreateView()方法内以编程方式为片段充气。然后你可以在你的活动布局xml中找到类似的东西:

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

<com.package.fragment_name
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    />

</FrameLayout>

然后,在您的活动中,您所要做的就是:

setContentView(R.layout.main);

因为片段是在布局xml中定义的,所以它不能从活动的布局中删除(虽然布局本身可以改变)并且与它相关联。

另外,在旁注中,请注意根视图是FrameLayout而不是片段本身。但是通过这种方式,您的片段可以与活动相关联。但请不要忘记片段仍会将其生命周期与活动分开。

编辑:如果您需要以编程方式创建片段实例,则必须执行以下操作:

getFragmentManager().beginTransaction().add(R.id.frame_layout, your_fragment).commit();

这是以编程方式添加片段的唯一方法。但请记住,Fragment的布局与活动的布局无关。但您可以使用Fragment的生命周期来表现与活动类似的行为。