我的应用中有一个MapFragment和常规片段。问题是当我在片段之间进行切换时,MapFragment就在后台。我有代码来查找MapFragment是否存在,但是我需要代码来删除它。
代码:
FragmentMapView mapFragmentcheck = (FragmentMapView)getFragmentManager().findFragmentByTag("map");
if (mapFragmentcheck != null) {
Log.d("tag","max exists");
if (mapFragmentcheck.isVisible()) {
Log.d("tag","map is visble, remove it");
// Do remove here, but how?
}
}
else {
Log.d("tag","map does not exists");
}
答案 0 :(得分:2)
试试这个
@Override
public void onDestroyView() {
super.onDestroyView();
MapFragment mapFragment = (MapFragment) getActivity()
.getFragmentManager().findFragmentById(R.id.map_add_place);
if (mapFragment != null)
getActivity().getFragmentManager().beginTransaction()
.remove(mapFragment).commit();
}

答案 1 :(得分:1)
代码如下:
getFragmentManager().beginTransaction().remove(mapFragmentcheck).commit();
请务必阅读FragmentTransaction
上的文档,以了解有关如何更改片段的更多信息。
答案 2 :(得分:0)
这对我有用
我正在添加Google Map
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.home_fragment, container, false);
Bundle bdl = getArguments();
// setuping locatiomanager to perfrom location related operations
locationManager = (LocationManager) getActivity().getSystemService(
Context.LOCATION_SERVICE);
// Requesting locationmanager for location updates
locationManager.requestLocationUpdates(
LocationManager.NETWORK_PROVIDER, 1, 1, this);
// To get map from MapFragment from layout
googleMap = ((MapFragment) getActivity().getFragmentManager()
.findFragmentById(R.id.map)).getMap();
// To change the map type to Satellite
// googleMap.setMapType(GoogleMap.MAP_TYPE_SATELLITE);
// To show our current location in the map with dot
// googleMap.setMyLocationEnabled(true);
// To listen action whenever we click on the map
googleMap.setOnMapClickListener(new OnMapClickListener() {
@Override
public void onMapClick(LatLng latLng) {
/*
* LatLng:Class will give us selected position lattigude and
* longitude values
*/
Toast.makeText(getActivity(), latLng.toString(),
Toast.LENGTH_LONG).show();
}
});
changeMapMode(3);
// googleMap.setSatellite(true);
googleMap.setTrafficEnabled(true);
googleMap.setBuildingsEnabled(true);
googleMap.setMyLocationEnabled(true);
return v;
}
我在xml中的地图看起来像这样
<fragment
android:id="@+id/map"
android:name="com.google.android.gms.maps.MapFragment"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:tag="ScrewMaps" />
我正在拆卸像这样的碎片: -
@Override
public void onDestroyView() {
// TODO Auto-generated method stub
super.onDestroyView();
locationManager.removeUpdates(this);
android.app.Fragment fragment = getActivity().getFragmentManager()
.findFragmentById(R.id.map);
if (null != fragment) {
android.app.FragmentTransaction ft = getActivity()
.getFragmentManager().beginTransaction();
ft.remove(fragment);
ft.commit();
}
}
请注意我的MapView片段是 android.app.Fragment &amp;我正在使用 getFragmentManager()来添加和删除MapViewFragment。如果您将V4.Fragment操作与app.Fragment混合,您的应用程序将崩溃