Android Fragment - onCreateView - 容器为空

时间:2014-12-05 00:29:43

标签: android android-fragments

我对onCreateView方法有一个小问题 - 给定的容器/父级是null,因此我不能给我的布局充气。这是我的代码:

这是我的"主要"类

public class DrawerActivity extends ActionBarActivity
        implements NavigationFragment.NavigationListener {
    private static final int DRAWER_DELAY = 250;

    private Toolbar toolbar;
    private NavigationFragment navigationFragment;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        // check if smartphone or tablet...
        if (isStaticMenuDrawer()) {
            setContentView(R.layout.activity_drawer_static);
        } else {
            setContentView(R.layout.activity_drawer);
        }

    }

    protected void createMenuDrawer(int contentViewId) {
        ViewGroup content = (ViewGroup) findViewById(R.id.content);
        content.addView(getLayoutInflater().inflate(contentViewId, null));

        navigationFragment = (NavigationFragment)
                getSupportFragmentManager().findFragmentById(R.id.drawer_fragment);
        navigationFragment.initDrawer(R.id.drawer_fragment, R.id.drawer_layout, toolbar);

    }
}

这是我的activity_drawer.xml

<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.DrawerLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/drawer_layout"
    android:layout_height="match_parent"
    android:layout_width="match_parent" >


    <FrameLayout
        android:id="@+id/content"
        android:layout_width="match_parent"
        android:layout_height="match_parent"/>

    <include layout="@layout/include_drawer"/>
    <include layout="@layout/include_toolbar"/>

</android.support.v4.widget.DrawerLayout>

这是我的OverviewActivity(我的启动器/默认活动)

public class OverviewActivity extends DrawerActivity {
    OverviewFragment overview;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        createMenuDrawer(R.layout.activity_overview);
    }
}

my activity_overview.xml

<?xml version="1.0" encoding="utf-8"?>
<fragment
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    class="com.xxxx.ui.overview.OverviewFragment"
    android:id="@+id/fragment_overview" />

和...我的片段

public class OverviewFragment extends Fragment {

    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_overview, container, false);
    }
}

任何人都可以解释一下,为什么容器是空的?谢谢...:)

1 个答案:

答案 0 :(得分:4)

使用静态方法时,您的<fragment>需要包含在视图组中。只需将RelativeLayout作为其父文件放在XML文件中。