Search code examples
androidbackwards-compatibilityandroid-support-library

How can I avoid deprecated methods and maintain backwards compatibility?


Possible Duplicate:
How to deal with deprecated classes in Android to keep compatibility

I ran into the deprecated Display.getWidth() method and saw that it has been replaced with android.view.getSize(). However getSize() has only been available since API 13 and View appears not to be included in the V4 Android support library.

So, if I want to avoid the deprecated calls, how can I do this without maintaining different projects/builds for various API levels.


Solution

  • Given a Display object named display, this should work:

    int width=-1;
    
    if (Build.VERSION.SDK_INT>=Build.VERSION_CODES.HONEYCOMB_MR2) {
        Point size=new Point();
        size=display.getSize(size);
        width=size.x;
    }
    else {
        width=display.getWidth();
    }
    

    IOW, use Build.VERSION.SDK_INT to branch between the "before" and "after" cases for where a new API is introduced.

    This will require your build target (Project > Properties > Android in Eclipse) to be set to API Level 13+, so you can call getSize().