Extending RelativeLayout, and overriding dispatchDraw() to create a zoomable ViewGroup

If you are applying a scale factor to the drawing of your children, you also need to apply the appropriate scale factor to all of the other interactions with them — dispatching touch events, invalidates, etc.

So in addition to dispatchDraw(), you will need to override and appropriate adjust the behavior of at least these other methods. To take care of invalidates, you will need to override this method to adjust the child coordinates appropriately:

http://developer.android.com/reference/android/view/ViewGroup.html#invalidateChildInParent(int[], android.graphics.Rect)

If you want the user to be able to interact with the child views you will also need to override this to adjust touch coordinates appropriately before they are dispatched to the children:

http://developer.android.com/reference/android/view/ViewGroup.html#dispatchTouchEvent(android.view.MotionEvent)

Also I would strongly recommend you implement this all inside of a simple ViewGroup subclass that has a single child view it manages. This will get rid of any complexity of behavior that RelativeLayout is introducing in its own ViewGroup, simplifying what you need to deal with and debug in your own code. Put the RelativeLayout as a child of your special zooming ViewGroup.

Finally, one improvement to your code — in dispatchDraw() you want to save the canvas state after applying the scaling factor. This ensures that the child can’t modify the transformation you have set.

Leave a Comment