Android - 以编程方式设置布局背景 [英] Android - set layout background programmatically

查看:47
本文介绍了Android - 以编程方式设置布局背景的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我注意到 RelativeLayout 对象的 setBackground 方法针对 API 16 (Android 4.1) 及更高版本,但我的应用程序具有目标 API 8 和我不能使用它.

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.

是否有其他解决方案可以解决此问题(除了使用 TargetApi(16) 标记类/方法或更改清单中的目标 API)?
谢谢!

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!

编辑:Eclipse 有问题,它向我显示了与 setBackgroundDrawable 相同的错误,但现在它似乎可以工作了.感谢您的帮助.

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

推荐答案

使用以下之一:

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

如果您使用第二个,请确保对您的 API 版本进行条件检查:

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(...);

...并用 @TargetApi(16)@SuppressWarnings("deprecation") 标记它.

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

这篇关于Android - 以编程方式设置布局背景的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆