23

I wanted to use view.setBackgroundDrawable(Drawable) but this method is deprecated. It is replaced with .setBackground(Drawable). But my minimum of API 8 can't handle that. It tells me to set the minimum to API 16.

Is there a way to use a different method, based on the API of the device?

Something like

if(API<16)
{
  view.setBackgroundDrawable(Drawable)
}
else
{
  view.setBackground(Drawable)
}

Or do I really have to change the minimum API to do this?

Anirudh Ramanathan
  • 46,179
  • 22
  • 132
  • 191
Niels
  • 1,340
  • 2
  • 15
  • 32

3 Answers3

40

setBackgroundDrawable is deprecated but it still works so you could just use it. But if you want to be completely correct you should use something like this

int sdk = android.os.Build.VERSION.SDK_INT;
if(sdk < android.os.Build.VERSION_CODES.JELLY_BEAN) {
    setBackgroundDrawable()
} else {
    setBackground();
}

For this to work you need to set buildTarget api 16 and min build to 7 or something similar.

Antrromet
  • 15,294
  • 10
  • 60
  • 75
7

Something like this:

if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN){
   view.setBackgroundDrawable(Drawable)
} else {
   view.setBackground(Drawable)
}
Simon
  • 14,407
  • 8
  • 46
  • 61
5

You can use different methods based on the API versions.

For e.g:

if (Build.VERSION.SDK_INT < Build.VERSION_CODES.FROYO) {
        //Methods for version <8 (FROYO)
} else {
        // Methods for version >=8
}

Here set your targetSDkversion to any higher versions(for e.g 16 here) and set your minsdkversion to lower versions ( API 7).

Renjith
  • 5,783
  • 9
  • 31
  • 42