将fragment移动到framelayout时,findFragmentById()返回null

时间:2014-10-04 23:00:28

标签: android android-fragments

这是我当前视图的.xml:

<!-- A DrawerLayout is intended to be used as the top-level content view using match_parent for both width and height to consume the full space available. -->
<android.support.v4.widget.DrawerLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/drawer_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".nav">

<!-- As the main content view, the view below consumes the entire
     space available using match_parent in both dimensions. -->
   <FrameLayout
    android:id="@+id/container"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >

   <fragment xmlns:android="http://schemas.android.com/apk/res/android"
       android:id="@+id/map"
       android:layout_width="match_parent"
       android:layout_height="match_parent"
       android:name="com.google.android.gms.maps.MapFragment"/>

   <ImageButton
       android:text="Center"
       android:onClick="centerMap"
       android:id="@+id/center_button"
       android:layout_alignParentBottom="true"
       android:layout_alignParentLeft="true"
       android:layout_alignParentStart="true"
       android:src="@drawable/center_button_iconn"
       android:layout_width="45dp"
       android:layout_height="55dp"
       android:layout_gravity="start|bottom" />

   <fragment android:id="@+id/navigation_drawer"
       android:layout_width="@dimen/navigation_drawer_width"
       android:layout_height="match_parent"
       android:layout_gravity="start"
       android:name="nuathackmit.yo.NavigationDrawerFragment"
       tools:layout="@layout/fragment_navigation_drawer" />

</FrameLayout>

<!-- android:layout_gravity="start" tells DrawerLayout to treat
     this as a sliding drawer on the left side for left-to-right
     languages and on the right side for right-to-left languages.
     If you're not building against API 17 or higher, use
     android:layout_gravity="left" instead. -->
<!-- The drawer is given a fixed width in dp and extends the full height of
     the container. -->


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

最初,我的片段(和ImageButton)存在于framelayout之外。但是,由于我希望组织上面出现的对象,我将它们移到了framelayout中。

然而:

mMap = ((MapFragment) getFragmentManager().findFragmentById(R.id.map)).getMap();

此代码最初工作的地方,现在返回NPE。

如何在移动到FrameLayout时按ID获取片段?

0 个答案:

没有答案