MattF
MattF

Reputation: 1494

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.

Upvotes: 1

Views: 287

Answers (3)

San
San

Reputation: 5697

Create two classes A and B. A for 2.2+ and B for 2.1 or earlier versions.

if(Build.VERSION.SDK_INT < 8) //2.2 version is 8
{
  Use the class B
}
else
{
 Use class A
}

Upvotes: 2

Shankar Agarwal
Shankar Agarwal

Reputation: 34765

Build.VERSION.RELEASE

use the above line to get the OS version of the device.

And you can have simple if else case. just check if the OS version is above 2.2 the you can have zoom in zoom out. else make it no zoom in or zoom out.

Upvotes: 1

idiottiger
idiottiger

Reputation: 5177

well, you can get ScaleGestureDetector source code and put in your project, make it as your own class, and use this to instead of system ScaleGestureDetector, this can avoid the android 2.2 and below version.

here is the ScaleGestureDetector source code: http://pastebin.com/r5V95SKe

Upvotes: 2

Related Questions