我正在使用谷歌地图android api开发一个应用程序。该应用程序显示用户可以打开和关闭的各种平铺。当我旋转设备时,重叠保持在原位,但当我单击按钮关闭重叠时,我的设备就好像控制重叠的变量为空一样。在这种情况下,我如何才能保持对我的tileoverlay的控制。
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
SupportMapFragment mapFragment =
(SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
//mMap=null;
if (savedInstanceState == null) {
// First incarnation of this activity.
mapFragment.setRetainInstance(true);
} else {
// Reincarnated activity. The obtained map is the same map instance in the previous
// activity life cycle. There is no need to reinitialize it.
mMap = mapFragment.getMap();
}
setUpMapIfNeeded();
setUpFieldsIfNeeded();
}
private void setUpMapIfNeeded() {
// Do a null check to confirm that we have not already instantiated the map.
if (mMap == null) {
// Try to obtain the map from the SupportMapFragment.
mMap = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map)).getMap();
}
}
}
private void setUpFieldsIfNeeded(){
if (fieldsOverlay == null) {
TileProvider tileProvider = new UrlTileProvider(256, 256) {
@Override
public synchronized URL getTileUrl(int x, int y, int zoom) {
//String s = String.format(Locale.US, CMAFieldsRequestFormat, zoom, x, y);
String s = String.format(Locale.US, cartoDBFieldsTile, zoom, x, y);
s =s.replace(" ", "%20");
System.out.println(s);
URL url = null;
try {
url = new URL(s);
} catch (MalformedURLException e) {
throw new AssertionError(e);
}
return url;
}
};
fieldsOverlay = mMap.addTileOverlay(
new TileOverlayOptions().tileProvider(tileProvider));
fieldsOverlay.setVisible(false);
fieldsOverlay.setZIndex(1);}
}
TLDR:我使用谷歌地图,上面有一个名为fieldsOverlay的tileOverlay。当我旋转设备时,覆盖本身会被保留,但它不再连接到变量字段overlay。解决这个问题的最佳方法是什么。
感谢
edit:通过运行mMap.clear,然后重新初始化我的层,并在我重新转换活动时将可见性设置为savedInstanceState值,我可以让应用程序看起来像我想要的那样运行,但这似乎不是一个好的解决方案。
使用SupportMapFragment.setRetainInstace
似乎是实现所需结果的快速方法,但事实并非如此。
首先,它会导致内存泄漏。查看我的gmaps-api问题以进行讨论。
你在那里遇到的问题很正常。重新创建Activity
时,将不会保留您保留的TileOverlay
引用。实际上创建了一个新的Activity
对象。视觉对象应该像普通的Android View
一样处理:配置更改时不保留。官方文件中甚至有关于这一点的注释,但我现在找不到了。
如果不使用setRetainInstance
,则不会出现对象没有引用的问题,因为必须在旋转时重新创建。