2015-04-17 21 views
8

Chciałbym dodać ten fragment xml programowo do innych fragmentów. Czy to możliwe?Jak programowo dodać fragment mapy?

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

http://stackoverflow.com/questions/13733299/initialize-mapfragment- programowo-z-mapami-api-v2 – Hulk

+0

Nie powinieneś wstawiać "fragmentu" wewnątrz innego "fragmentu". Byłoby lepiej wstawić go w nowym 'activity' przez' FragmentTransaction', jeśli nie chcesz używać układu XML. – moictab

Odpowiedz

13

W XML można dodać pojemnik zastępczy:

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

A potem w kodzie można zrobić:

FragmentManager fm = getChildFragmentManager(); 
SupportMapFragment supportMapFragment = SupportMapFragment.newInstance(); 
fm.beginTransaction().replace(R.id.mapContainer, supportMapFragment).commit(); 
+0

nie można rozwiązać metody: getChildFragmentManager(); zaktualizuj także min api do 17, a następnie jak to rozwiązać? –

+2

@JosephMekwan o getChildFragmentManager(). Dla jasności, jeśli próbujesz wstawić fragment w Activity, musisz użyć getSupportFragmentManager() lub getFragmentManager(). Gdzie jest getChildFragmentManager() używany wewnątrz fragmentu, jeśli chcesz mieć wewnętrzny fragment. Jeśli masz API 17 lub więcej, musi być gdzieś tam. –

+1

To prawda, ale musisz dodać "supportMapFragment.getMapAsync (this);" obsłużyć mapę i zastąpić metodę onMapReady (GoogleMap googleMap) – Terranology

2

Zrób układ jak:

<FrameLayout 
    android:id="@+id/layout_mapContainer" 
    android:layout_width="match_parent" 
    android:layout_height="wrap_content" 
    android:layout_margin="5dp" 
    android:layout_weight="0" 
    android:background="@android:color/transparent" 
    android:orientation="vertical" > 

<FrameLayout 
    android:layout_width="match_parent" 
    android:layout_height="match_parent" 
    android:background="@android:color/transparent" /> 
</FrameLayout> 

W deklarują aktywny:

FrameLayout mapLayout = (FrameLayout)findViewById(R.id.layout_mapContainer); 

Uruchomienie map tak:

private void initialiseMap() { 

     FragmentTransaction mTransaction = getSupportFragmentManager().beginTransaction(); 
     SupportMapFragment mFRaFragment = new MapFragmentActivity(); 
     mTransaction.add(mapLayout.getId(), mFRaFragment); 
     mTransaction.commit(); 

     try { 
      MapsInitializer.initialize(context); 
     } catch (Exception e) { 
      e.printStackTrace(); 
     } 

    } 

Tutaj MapFragmentActivity jest klasa rozszerza SupportMapFragment

Powiązane problemy