使用FragmentManager和FragmentTransaction

时间:2017-03-05 05:26:07

标签: java android google-maps android-layout android-fragments

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

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是包含Map片段的布局:



<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>
&#13;
&#13;
&#13;

所以我想做的就是我想使用像普通片段一样的Fragment事务将这个片段添加到另一个活动中。

1 个答案:

答案 0 :(得分:1)

将此地图片段添加到Fragment(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="+@id/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(); 

希望这有帮助。