2013-07-29 117 views
2

我正在實現和Android應用程序,我試圖在另一個片段中使用SupportMapFragment。 地圖片段工作正常,我可以看到地圖,我沒有得到任何錯誤。 但是,在主要活動中,我試圖從嵌套的片段獲取GoogleMap對象,但是我得到的全部爲空。任何想法我怎麼能克服這一點?SupportMapFragment嵌套在另一個片段

main_activity.xml

<?xml version="1.0" encoding="utf-8"?> 
<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" /> 

片段layout.xml

<?xml version="1.0" encoding="utf-8"?> 
<LinearLayout 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:orientation="vertical" 
    android:background="#E8E8E8"> 

     <fragment 
      android:id="@+id/map" 
      android:name="com.google.android.gms.maps.SupportMapFragment" 
      android:layout_width="match_parent" 
      android:layout_height="117dp" 
      android:layout_margin="5dp" /> 
<LinearLayout/> 
在MainActivity.java::onCreate()

// Getting reference to the SupportMapFragment of activity_main.xml 
     SupportMapFragment fm = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map); 

     //fm is null here 
+0

你的活動類是否擴展'FragmentActivity'? – Raghunandan

+0

@Raghunandan yes,.... extends FragmentActivity implements \t \t ActionBar.TabListener { – maephisto

+0

您可以發佈堆棧跟蹤。 – Raghunandan

回答

1

目前還不清楚,你實際上是在這裏有「嵌套片段」。我只看到一個片段:SupportMapFragment

如果您ViewPager是片段裏面,你FragmentPagerAdapter使用SupportMapFragment,那麼你需要在孩子FragmentManager,即FragmentPagerAdapter使用一個被調用findFragmentById()

如果您的ViewPager不在片段內,那麼我不認爲您有嵌套片段。但是,您的ViewPager可能尚未實例化您的整體活動的onCreate()中的任何頁面,因此您的片段尚不存在。等到您的FragmentPagerAdapter已創建您的SupportMapFragment,,然後嘗試使用它。