setBackground vs setBackgroundDrawable (Android)

Pijusn picture Pijusn · Aug 14, 2012 · Viewed 207.8k times · Source

I want to set background drawable of a view. There are two methods for this (as far as I see): setBackground and setBackgroundDrawable.

When I use setBackground, it says it has been added in API level 16 but my project's min SDK version is 7. I assume it's not going to work on anything below 16, am I right? But when I use setBackgroundDrawable, it says it's deprecated.

What am I supposed to use?

Answer

Warpzit picture Warpzit · Aug 14, 2012

It's deprecated but it still works so you could just use it. But if you want to be completly correct, just for the completeness of it... You'd do something like following:

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.