Android - set layout background programmatically

后端 未结 3 1381
旧巷少年郎
旧巷少年郎 2020-12-09 21:04

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 targ

3条回答
  •  悲&欢浪女
    2020-12-09 21:40

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

提交回复
热议问题