9

I have noticed that the setBackground method for the RelativeLayout object is targeted for API 16 (Android 4.1) and higher, but my application has the target API 8 and I cannot use it.

Is there any alternative solution for this problem (besides marking the class/method with TargetApi(16) or changing the target API in the manifest)?
Thank you!

Edit: Eclipse was buggy and it showed me the same error for setBackgroundDrawable but now it seems to work. Thank you for your help.

davehale23
  • 4,374
  • 2
  • 27
  • 40
sethengine
  • 93
  • 1
  • 2
  • 5

3 Answers3

30

Use one of:

If you use the second one, make sure to do a conditional check on your API version:

if (Build.VERSION.SDK_INT >= 16)
    view.setBackground(...);
else
    view.setBackgroundDrawable(...);

... and mark it with @TargetApi(16) and @SuppressWarnings("deprecation").

Eng.Fouad
  • 115,165
  • 71
  • 313
  • 417
Cat
  • 66,919
  • 24
  • 133
  • 141
  • 1
    ah I know of the .setBackgroundDrawable(Drawable) method but to me the IDE had the same error with api 16 requirement. I am using Eclipse and it seemed to be a bug after reopening the ide and cleaning the code a bit it worked. Than you very much and sorry for trouble. – sethengine Oct 01 '12 at 19:46
  • 1
    @sethengine Don't worry about the trouble--we're here to help! Glad you've solved the issue. – Cat Oct 01 '12 at 21:06
1

It depends. If you want to set a color as the background, use setBackgroundColor(). For a Drawable, you can use the now deprecated method setBackgroundDrawable() for APIs below 16, and setBackground() for API 16 devices. You can also use setBackgroundResource() for setting a resource as the background.

Note that while a lot of methods are marked as deprecated, I'm yet to come across one that has actually been removed. So while you could use the deprecated method even in API 16, I'd recommend setting your target API to 16 and using an if else to switch between the methods, depending on the API version the device is running.

Raghav Sood
  • 81,899
  • 22
  • 187
  • 195
0

Use setBackgroundDrawable() instead. It does the same thing, but it's been deprecated since the new setBackground() method.

Samuel
  • 16,923
  • 6
  • 62
  • 75