Android:从子类向活动发送消息

时间:2012-07-05 12:33:31

标签: android android-activity broadcastreceiver

我有以下自定义的MapView,每次缩放地图时都会记录“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();
        }

    }
}

以下是我的onCreate(...)活动的片段:

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

现在如何将“ZOOMED”消息收到我的活动中?!我想在用户缩放后刷新地图图标的位置......

我试过看过BroadcastReceivers,但我不确定这是怎么回事?

非常感谢,

1 个答案:

答案 0 :(得分:1)

您可以在CustomMapView课程中编写一个简单的听众:

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();
        }
    }
}

在您的活动中

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