Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android - set layout background programmatically

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.

like image 339
sethengine Avatar asked Oct 01 '12 18:10

sethengine


People also ask

How to set button background programmatically in Android?

setBackgroundResource() method is used to change the button background programmatically. setBackgroundResource(int id) accepts id of drawable resource and applies the background to the button.


2 Answers

Use one of:

  • .setBackgroundColor(int) (if you're setting it to a color)
  • .setBackgroundDrawable(Drawable) (if you're setting it to a Drawable type; this is deprecated, and was replaced by .setBackground(Drawable))
  • .setBackgroundResource(int) (for setting a resource from R.java)

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

like image 91
Cat Avatar answered Sep 25 '22 02:09

Cat


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.

like image 35
Raghav Sood Avatar answered Sep 24 '22 02:09

Raghav Sood