我正在使用新的GoogleMaps API(v2)并且片段存在一些问题 . 我的应用程序(Map,List)中有两个片段,用户可以在它们之间切换 . 到目前为止使用此代码正常工作:
if (itemPosition == 0) {
getSupportFragmentManager().beginTransaction()
.replace(R.id.fragmentpos, myMapFragment).commit();
} else if (itemPosition == 1) {
getSupportFragmentManager().beginTransaction()
.replace(R.id.fragmentpos, myListFragment).commit();
}......
当我使用 Map 时,切换到列表片段,然后返回到 Map 片段,不保存 Map 的最后位置 . 这不是我想要的,我希望 Map 处于保存状态,因为我“离开”它..我怎么能完成这个?我试图保存相机的位置
public void onSaveInstanceState(Bundle outState){
outState.putDouble("LAT", mMap.getCameraPosition().target.latitude);
outState.putDouble("LON", mMap.getCameraPosition().target.longitude);
outState.putFloat("BEAR", mMap.getCameraPosition().bearing);
...
}
并在onCreateView()中恢复它,但Bundle始终为null . 如果我替换片段,则不会调用onSaveInstanceState .
那么如何保存 Map 的状态呢?
2 回答
如果你是一个片段,旧片段的视图会被销毁,这会取出你的
MapView
,大概是CameraPosition
.onSaveInstanceState()
主要用于配置更改,例如屏幕旋转 .MapFragment
和SupportMapFragment
已经保留CameraPosition
(其中,BTW,是Parcelable
,因此您可以将整个对象保存在Bundle
而不是零碎) .您可以考虑使用
show()
和hide()
而不是replace()
,因此片段及其视图会一直存在 .我通过在片段的
onDestroyView()
方法中继续对 Map 上的CameraPosition
的引用来解决这个问题;然后在重新安装 Map 时使用CameraPosition
.我的解决方案的上下文有's own quirks, but essentially I have a map fragment nested within another fragment (which I' m挂在上面,即使它得到's replaced). So this is the code in the parent fragment' s
onActivityCreated()
方法:然后我在同一个 class :