Search code examples
androidandroid-activitybroadcastreceiver

Android: send a message from a subclass to an activity


I have the following customised MapView that logs "ZOOMED" every time the map is zoomed.

import android.content.Context;
import android.graphics.Canvas;
import android.util.AttributeSet;
import android.util.Log;
import com.google.android.maps.MapView;

public class CustomMapView extends MapView{

    int oldZoomLevel=0;

    public CustomMapView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    @Override
    protected void dispatchDraw(Canvas canvas) {
        super.dispatchDraw(canvas);
        if (getZoomLevel() != oldZoomLevel) {
            Log.i("EOH", "ZOOOMED");

            oldZoomLevel = getZoomLevel();
        }

    }
}

Here is a snippet from my onCreate(...) Activity:

...
mapView = (CustomMapView) findViewById(R.id.map);
mapView.setBuiltInZoomControls(true);
mapOverlays = mapView.getOverlays();
...

Now how do I get the message "ZOOMED" into my Activity?! I want to refresh the position of the map's icons once the user zooms...

I've tried looking at BroadcastReceivers, but I'm not sure this is the way to go about it?

Many thanks in advance,


Solution

  • You can write a simple listener in your CustomMapView class:

    public class CustomMapView extends MapView{
    
        public interface MapZoomListener {
    
            public void onZoom();
        }
    
        private MapZoomListener mListener;
    
        public void setZoomListener(MapZoomListener listener){
            mListener = listener;
        }
    
        // ... 
    
        @Override
        protected void dispatchDraw(Canvas canvas) {
            super.dispatchDraw(canvas);
            if (getZoomLevel() != oldZoomLevel) {
                Log.i("EOH", "ZOOOMED");
                mListener.onZoom();
                oldZoomLevel = getZoomLevel();
            }
        }
    }
    

    In your Activity

    ...
    mapView = (CustomMapView) findViewById(R.id.map);
    mapView.setZoomListener(new CustomMapView.MapZoomListener {
        public void onZoom(){
            // Your logic here
        }
    });
    mapView.setBuiltInZoomControls(true);
    mapOverlays = mapView.getOverlays();
    ...