简体   繁体   English

Android - 以编程方式设置布局背景

[英]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. 我注意到RelativeLayout对象的setBackground方法是针对API 16(Android 4.1)及更高版本的,但我的应用程序具有目标API 8,我无法使用它。

Is there any alternative solution for this problem (besides marking the class/method with TargetApi (16) or changing the target API in the manifest)? 是否有针对此问题的替代解决方案(除了使用TargetApi (16)标记类/方法或更改清单中的目标API)?
Thank you! 谢谢!

Edit : Eclipse was buggy and it showed me the same error for setBackgroundDrawable but now it seems to work. 编辑 :Eclipse是错误的,它向我展示了setBackgroundDrawable的相同错误,但现在它似乎工作。 Thank you for your help. 谢谢您的帮助。

Use one of: 使用以下之一:

If you use the second one, make sure to do a conditional check on your API version: 如果您使用第二个,请确保对您的API版本进行条件检查:

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

... and mark it with @TargetApi(16) and @SuppressWarnings("deprecation") . ...并使用@TargetApi(16)@SuppressWarnings("deprecation")标记它。

It depends. 这取决于。 If you want to set a color as the background, use setBackgroundColor() . 如果要将颜色设置为背景,请使用setBackgroundColor() For a Drawable, you can use the now deprecated method setBackgroundDrawable() for APIs below 16, and setBackground() for API 16 devices. 对于Drawable,您可以对16以下的API使用现已弃用的方法setBackgroundDrawable() ,对API 16设备使用setBackground() You can also use setBackgroundResource() for setting a resource as the background. 您还可以使用setBackgroundResource()将资源设置为背景。

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. 因此,即使在API 16中您也可以使用已弃用的方法,我建议您将目标API设置为16并使用if else在方法之间切换,具体取决于设备运行的API版本。

Use setBackgroundDrawable() instead. 请改用setBackgroundDrawable() It does the same thing, but it's been deprecated since the new setBackground() method. 它做了同样的事情,但自从新的setBackground()方法以来它已被弃用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM