osmdroid中ItemizedOverlayWithFocus更换标记图标后点击异常咨询
Hey there, let's tackle this annoying issue where your marker descriptions are popping up on the wrong marker after customizing the icon!
The Root Cause
The problem here is that you're reusing the same Drawable instance for all your OverlayItems. Drawables in Android hold internal state (like focus, bounds, etc.), and when multiple items share the same Drawable, osmdroid gets confused about which marker should display the description. It ends up attaching the description to the wrong marker because the state is shared across all instances.
The Fix
You need to create a new, independent Drawable instance for each OverlayItem. You can do this either by fetching a fresh Drawable from resources each time, or using mutate() to make the Drawable state-independent.
Here's how to adjust your loop code:
final Context context = getActivity(); final ArrayList<OverlayItem> items = new ArrayList<>(); OverlayItem overlayItem; for (Hospital h : hospitals) { // Create a new Drawable instance for each marker (with mutate() to ensure independent state) Drawable marker = getResources().getDrawable(R.drawable.ic_hospital_).mutate(); overlayItem = new OverlayItem( h.getName(), h.getAdresse(), new GeoPoint(h.getLatitude(), h.getLongitude()) ); overlayItem.setMarker(marker); items.add(overlayItem); }
Bonus: Clean Up Your Focus Listener
Your current OnFocusChangeListener has code that manually resets and sets the focused item, which might be interfering with the default behavior of ItemizedOverlayWithFocus. Since the component already handles focus switching automatically, you can simplify this listener (or even remove it if you don't need custom logic):
itemizedOverlayWithFocus.setOnFocusChangeListener(new ItemizedOverlay.OnFocusChangeListener() { @Override public void onFocusChanged(ItemizedOverlay<?> overlay, OverlayItem newFocus) { // Remove the manual focus manipulation - let the component handle it // itemizedOverlayWithFocus.unSetFocusedItem(); // itemizedOverlayWithFocus.setFocusedItem(newFocus); } });
Why This Works
mutate()ensures each Drawable has its own state, so osmdroid can correctly track which marker is focused and attach the description to the right one.- Removing the manual focus calls prevents conflicting with the component's built-in focus management.
Give these changes a try, and your marker descriptions should now show up exactly where you tap!
内容的提问来源于stack exchange,提问作者Mustapha Bounoua

