Wednesday, April 25, 2012

How to use an API level 8 class when possible, and do nothing otherwise

I have a custom view in my Android App that uses a ScaleGestureDetector.SimpleOnScaleGestureListener to detect when the user wants to scale the view via a 2 finger pinch in or out. This works great until I tried testing on an Android 2.1 device, on which it crashes immediately because it cannot find the class.



I'd like to support the pinch zoom on 2.2+ and default to no pinch zoom <2.1. The problem is I can't declare my:



private class ScaleListener extends ScaleGestureDetector.SimpleOnScaleGestureListener
{
@Override
public boolean onScale(ScaleGestureDetector detector)
{
MyGameActivity.mScaleFactor *= detector.getScaleFactor();

// Don't let the object get too small or too large.
MyGameActivity.mScaleFactor = Math.max(0.1f, Math.min(MyGameActivity.mScaleFactor, 1.0f));

invalidate();
return true;
}
}


at all on android <2.1. Is there a clever way to get around this using java reflection? I know how to test if a method exists via reflection, but can I test if a class exists? How can I have my



private ScaleGestureDetector mScaleDetector;


declared at the top of my class if the API can't even see the ScaleGestureDetector class?



It seems like I should be able to declare some sort of inner interface like:



public interface CustomScaleDetector
{
public void onScale(Object o);
}


And then somehow...try to extend ScaleGestureDetector depending on if reflection tells you that the class is accessible...



But I'm not really sure where to go from there. Any guidance or example code would be appreciated, let me know if it isn't clear what I'm asking.





No comments:

Post a Comment