2015-01-04 101 views
1

我有一個帶有Google Maps片段和其他片段的導航抽屜的應用程序。我將以編程方式創建SupportMapFragment,並將其放入地圖容器中的自定義fragment_map佈局中。無法在片段內保留SupportMapFragment

的問題是我有超過2000+標記添加到數據庫中,從地圖,不想每次設備得到了旋轉再次填充。我認爲setRetainInstance(true)將解決問題,但它的無法正常工作 - 我得到一個全新的地圖,沒有標記和攝像頭在0,0位置的方向變化。示例應用程序工作正常,但仍然使用FragmentActivity,這不是我的情況。這裏的碎片有什麼問題?

GoogleMapsFragment.java:

public class GoogleMapsFragment extends Fragment implements OnMapReadyCallback { 

private SupportMapFragment mapFragment; 

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

    FragmentManager fm = getChildFragmentManager(); 
    mapFragment = (SupportMapFragment) fm.findFragmentById(R.id.map_container); 
    if (mapFragment == null) { 
     mapFragment = SupportMapFragment.newInstance(); 
     mapFragment.getMapAsync(this); 
     mapFragment.setRetainInstance(true); 
     fm.beginTransaction().add(R.id.map_cont, mapFragment).commit(); 
    } 
    return rootView; 
} 

@Override 
public void onMapReady(GoogleMap googleMap) { 
    googleMap.addMarker(new MarkerOptions().position(new LatLng(5, 5))); 

    // a long code with map initialization and adding markers here 
    // ... 
} 
} 
+0

我認爲這是因爲嵌套的片段。請參閱此鏈接http://stackoverflow.com/questions/14850573/cant-retain-nested-fragments – Krish

回答

0

默認情況下,當配置變化,如方位,整個活動重新啓動,但是你可以阻止它通過指定活動時能處理這樣做本身,這意味着你可以告訴活動不重新啓動,而是打電話onConfigurationChanged

閱讀更多關於它在這裏: how can I save the fragment? when I rotate the screen