2017-03-05 54 views
0

我一直在寻找很多关于添加地图片段到一个活动和执行片段事务添加和删除地图片段就像普通片段。我发现很多旧的帖子在stackoverflow但其中大多数用户使用getMap()方法获取googleMap对象,但当前版本的map没有getMap()方法,但它具有getMapAsync(),所以我找到的解决方案并非我寻找的解决方案。 我发现有人使用这也 GoogleMap map=((MapFragment)getActivity().getFragmentManager().findFragmentById(R.id.map)).getMap()但这里还getMap()未定义在当前版本的地图。所以任何人都可以请给我一个适当的指导来实现。 下面是代码,我要怎么实现这一点:使用FragmentManager和FragmentTransaction动态地添加地图片段到一个活动

public class MainActivity extends Fragment{ 
GoogleMap map; 
MapView v; 
@Nullable 
@Override 
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { 
    View view=inflater.inflate(R.layout.activity_main,container,false); 
    return view; 
} 

}

哪里activity_main是包含地图片段的布局:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" 
 
    xmlns:tools="http://schemas.android.com/tools" 
 
    android:id="@+id/activity_main" 
 
    android:layout_width="match_parent" 
 
    android:layout_height="match_parent" 
 
    tools:context="com.example.kamaloli.mapdemo.MainActivity"> 
 
    <fragment xmlns:android="http://schemas.android.com/apk/res/android" 
 
     xmlns:tools="http://schemas.android.com/tools" 
 
     android:id="@+id/main_activity_map" 
 
     android:name="com.google.android.gms.maps.SupportMapFragment" 
 
     android:layout_width="match_parent" 
 
     android:layout_height="match_parent" 
 
     tools:context="com.example.kamaloli.mapdemo.MainActivity" /> 
 
</RelativeLayout>

因此,所有我想要做的是我想使用Fragment事务将此片段添加到另一个活动中,如正常的片段换货。

+0

你可以把这个地图片段放在一个片段中,然后用这个片段替换活动 – tahsinRupam

+0

你可以举个例子吗? –

+0

当然,等一下。 – tahsinRupam

回答

1

此映射片段添加到片段(MapFragment)布局文件:

 <com.google.android.gms.maps.MapView 
     android:id="@+id/map" 
     android:layout_width="match_parent" 
     android:layout_height="match_parent"/> 

申报的MapView并公开使用GoogleMap:

private MapView mapView; 
private GoogleMap googleMap; 

添加以下代码以onViewCreated():

mapView = (MapView) view.findViewById(R.id.map); 
mapView.onCreate(savedInstanceState); 
mapView.onResume(); 
mapView.getMapAsync(this); 

将OnMapReadyCallback实现到您的片段并添加此方法:

@Override 
public void onMapReady(GoogleMap map) { 
    googleMap = map; 
} 

在activity_main.xml中添加一个容器:

 <FrameLayout 
     android:id="[email protected]/container" 
     android:layout_width = "match_parent" 
     android:layout_height = "match_parent"> 

     // Add all activity contents here 

    <FrameLayout/> 

与MapFragment替换此容器:

FragmentManager fm = getFragmentManager(): 
fm.beginTransaction.replace(R.id.container, new MapFragment()).commit(); 

希望这有助于。

+0

它不工作。它说不兼容类型“无法将片段转换为GoogleMap”对象,并且getMap()方法也不可用,但存在getMapAsync()。 –

+0

我改变了我的答案。现在你不必使用getMap()。它也已被弃用。而是使用getMapAsync。而且,你不应该在片段中调用片段。改用mapview。我已经改变了我的答案。请检查更新后的答案。 – tahsinRupam

+1

有工作就像魅力。谢谢tahsinRupam的帮助和时间。 –