Вызов showInfoWindow() во второй раз не обновляет информационное окно
Вот в чем дело: у меня есть карта с маркерами на ней (управляемая ClusterManager), и я показываю информационное окно каждый раз, когда на них нажимают. Я также выбираю их адрес в тот момент, когда на них нажимают, поэтому, как только я получу его, я снова вызываю showInfoWindow() для маркера, чтобы обновить его. Проблема в том, что адрес не будет отображаться в информационном окне. Вот мой InfoWindowAdapter (у меня есть два представления в зависимости от типа маркера, по которому щелкают):
class CabinetInfoWindowAdapter implements GoogleMap.InfoWindowAdapter {
public CabinetInfoWindowAdapter () {
}
@Override
public View getInfoWindow(Marker marker) {
// Use the default info window frame
return null;
}
@Override
public View getInfoContents(Marker marker) {
Cabinet cabinet = clickedCabinetMarker.getCabinet();
Log.i("fttxgr", "info contents, cabinet type: " + cabinet.getType().toString());
switch (cabinet.getType()) {
case ADSL:
case VDSL:
return getCabinetView(cabinet, marker);
case DSLAM:
return getDslamView(cabinet, marker);
default: return null;
}
}
private final View getCabinetView (final Cabinet cabinet, final Marker marker) {
View view = getLayoutInflater().inflate(R.layout.cabinet_info_window, null);
TextView cabinetId = (TextView) view.findViewById(R.id.cabinet_id);
TextView cabinetType = (TextView) view.findViewById(R.id.cabinet_type);
TextView cabinetAddress = (TextView) view.findViewById(R.id.cabinet_address);
TextView cabinetCoordinates = (TextView) view.findViewById(R.id.cabinet_coordinates);
TextView cabinetUserNick = (TextView) view.findViewById(R.id.cabinet_user_nick);
ImageView cabinetImage = (ImageView) view.findViewById(R.id.cabinet_image);
View header = view.findViewById(R.id.header);
cabinetId.setText (cabinet.getId() + " - " + cabinet.getCabinetNumber());
cabinetType.setText (cabinet.getType().toString());
switch (cabinet.getType()) {
case ADSL:
header.setBackgroundColor(getResources().getColor(R.color.adsl_red));
break;
case VDSL:
header.setBackgroundColor(getResources().getColor(R.color.vdsl_green));
break;
}
cabinetCoordinates.setText(cabinet.getCoordinates().toString());
if (cabinet.getImage() == null) {
loadCabinetImage(marker);
} else {
cabinetImage.setImageBitmap(cabinet.getImage());
}
if (cabinet.getUserNick() == null) {
loadCabinetUserNick(cabinet, cabinet.getUserId(), cabinet.getmUserSite(), marker);
} else {
cabinetUserNick.setText("Added by user: " + cabinet.getUserNick());
}
if (cabinet.getAddress() == null) {
loadCabinetAddress(cabinet.getCoordinates().latitude,
cabinet.getCoordinates().longitude, marker);
} else {
cabinetAddress.setText("Address: " + cabinet.getAddress());
}
return view;
}
private final View getDslamView (final Cabinet cabinet, final Marker marker) {
View view = getLayoutInflater().inflate(R.layout.dslam_info_window, null);
TextView dslamId = (TextView) view.findViewById(R.id.dslam_id);
TextView dslamAddress = (TextView) view.findViewById (R.id.dslam_address);
TextView dslamCoordinates = (TextView) view.findViewById (R.id.dslam_coordinates);
dslamId.setText(cabinet.getId() + " - " + cabinet.getCabinetNumber());
dslamCoordinates.setText(cabinet.getCoordinates().toString());
if (cabinet.getAddress() == null) {
Log.i("fttxgr", "address is null");
loadCabinetAddress(cabinet.getCoordinates().latitude,
cabinet.getCoordinates().longitude, marker);
} else {
Log.i("fttxgr", "address is there: " + cabinet.getAddress());
dslamAddress.setText("Address: " + cabinet.getAddress());
}
return view;
}
}
И функция loadCabinetAddress():
private void loadCabinetAddress (final double lat, final double lng, final Marker marker) {
Geocoder geocoder;
List<Address> addresses;
geocoder = new Geocoder(this, Locale.getDefault());
try {
addresses = geocoder.getFromLocation(lat, lng, 1);
String address = addresses.get(0).getAddressLine(0);
String city = addresses.get(0).getLocality();
String country = addresses.get(0).getCountryName();
String postalCode = addresses.get(0).getPostalCode();
String concat = "" +
((address != null) ? address : "") + " - " +
((city != null) ? city : "") + " - " +
((country != null) ? country : "") + " - " +
((postalCode != null) ? postalCode : "");
clickedCabinetMarker.getCabinet().setAddress(concat);
Log.i("fttxgr", "address loaded, showing info window again");
marker.showInfoWindow();
} catch (IOException e) {
e.printStackTrace();
}
}
Все журналы показывают, что все идет как положено. Так почему же информационное окно не обновляется должным образом?
PS Самое смешное, что для первого просмотра (возвращенного getCabinetView()) обновление работает! Но я также асинхронно загружаю изображение и псевдоним пользователя и трижды вызываю showInfoWindow(), чтобы обновить их все.
1 ответ
Вы можете напрямую использовать setOnClusterItemClickListener
метод, если вы хотите поместить информационное окно для каждого элемента в кластере, или если вы хотите поместить одно информационное окно для всего кластера, вы можете создать его, используя setOnClusterClickListener
метод вместо того, чтобы делать всю эту тяжелую работу.
Создайте ClusterManager и установите информационное окно с помощью адаптера:
ClusterManager<MarkerItem> clusterMgr = new ClusterManager<MarkerItem>(context, map);
map.setInfoWindowAdapter(clusterMgr.getMarkerManager());
Создайте infowindowadapter
для одного из них:
clusterMgr.getMarkerCollection().setOnInfoWindowAdapter(new MyCustomAdapterForItems());
Последняя часть - это сопоставление необработанного объекта Marker, который вы получите в обратном вызове вашего пользовательского InfoWindowAdapter, с объектами ClusterItem, которые вы добавили на карту в первую очередь. Это может быть достигнуто с помощью прослушивателей onClusterClick и onClusterItemClick следующим образом:
map.setOnMarkerClickListener(clusterMgr);
clusterMgr.setOnClusterItemClickListener(new OnClusterItemClickListener<MarkerItem>() {
@Override
public boolean onClusterItemClick(MarkerItem item) {
clickedClusterItem = item;
return false;
}
});