我正在使用谷歌地图android api开发一个应用程序。该应用程序显示用户可以打开和关闭的各种tileoverlay。当我旋转设备时,覆盖图保持不变,但是当我单击按钮关闭覆盖时,我的设备就好像控制覆盖的变量为空。在这种情况下,如何保持对我的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的谷歌地图。当我旋转设备时,覆盖层本身会被保留,但它不再连接到变量fieldsOverlay。解决此问题的最佳方法是什么。
由于
编辑:我能够通过运行mMap.clear然后重新初始化我的图层并在我重新启动我的活动时将可见性设置为savedInstanceState值来让应用程序看起来按照我想要的方式运行,但这似乎不像一个好的解决方案
答案 0 :(得分:1)
使用SupportMapFragment.setRetainInstace
似乎是实现预期结果的快捷方式,但事实并非如此。
首先,它会导致内存泄漏。查看我的gmaps-api-issue进行讨论。
你遇到的问题很正常。重新生成TileOverlay
时,您保留的Activity
引用将不会被保留。实际上创建了一个新的Activity
对象。视觉对象应该像普通的Android View
一样对待:配置更改时不保留。在the official documentation中甚至有一个关于此的说明,但我现在找不到它。
如果你不使用setRetainInstance
,你就不会有没有引用你的对象的问题,因为你必须在轮换时再次创建。