我有一个带有三个列表项的导航抽屉。第一个显示带有文本视图的片段,第二个显示带有地图的片段。当我单击选项以显示地图片段时,它可以正常工作,当我再次切换到第一个片段时它会起作用,但是当我再次尝试点击地图片段时它会崩溃。
我的地图片段类看起来像:
public class FragmentTwo extends Fragment {
GoogleMap map;
public static Fragment newInstance(Context context) {
FragmentTwo f = new FragmentTwo();
return f;
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {
View root = (ViewGroup) inflater.inflate(R.layout.fragment_two, null,false);
if (root != null) {
ViewGroup parent = (ViewGroup) root.getParent();
if (parent != null)
parent.removeView(root);
}
try {
root = inflater.inflate(R.layout.fragment_two, container, false);
} catch (InflateException e) {
/* map is already there, just return view as it is */
}
setUpMapIfNeeded();
return root;
}
@Override
public void onResume() {
super.onResume();
setUpMapIfNeeded();
}
@Override
public void onPause() {
super.onPause();
setUpMapIfNeeded();
}
@Override
public void onDestroy() {
super.onDestroy();
}
private void setUpMapIfNeeded() {
// Do a null check to confirm that we have not already instantiated the map.
if (map == null) {
// Try to obtain the map from the SupportMapFragment.
map = ((SupportMapFragment) getFragmentManager().findFragmentById(R.id.map)).getMap();
// Check if we were successful in obtaining the map.
if (map != null) {
setUpMap();
}
}
}
private void setUpMap() {
LatLng sydney = new LatLng(-33.867, 151.206);
map.setMapType(GoogleMap.MAP_TYPE_TERRAIN);
map.setMyLocationEnabled(true);
map.moveCamera(CameraUpdateFactory.newLatLngZoom(sydney, 13));
map.addMarker(new MarkerOptions()
.title("Sydney")
.snippet("The most populous city in Australia.")
.position(sydney));
}}
我的xml看起来像:
<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 :(得分:0)
删除此行
View root = (ViewGroup) inflater.inflate(R.layout.fragment_two, null,false);
并在MainActivity中进行初始化
FragmentTwo f = new FragmentTwo();
在Oncreate中 当你需要交换到这个片段时,你可以使用
FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction()
.replace(R.id.frame_container, f).commit();