Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I avoid deprecated methods and maintain backwards compatibility? [duplicate]

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.

like image 249
Jeff Axelrod Avatar asked Sep 10 '12 13:09

Jeff Axelrod


People also ask

Is it OK to use deprecated methods?

A deprecated class or method is like that. It is no longer important. It is so unimportant, in fact, that you should no longer use it, since it has been superseded and may cease to exist in the future.

Is it OK to use deprecated packages?

It means that it is bad practice to use it. It can still be used, but eventually it will not work with other things because it is no longer being supported. Best practice is to use the requested alternative to any depreciated type.


1 Answers

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().

like image 199
CommonsWare Avatar answered Sep 19 '22 02:09

CommonsWare