3

I have a project which is compatible with Android versions from 10(GINGERBREAD_MR1) to 17(JELLY_BEAN_MR1).

So, I would like to use setBackgroundDrawable for versions lower to 16 and setBackground from version 16 or upper.

I've tried this:

if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN) {
    subMessageFromToLinearLayout.setBackgroundDrawable(null);
} else {
    subMessageFromToLinearLayout.setBackground(null);
}

But, Eclipse gives me:

A warning for subMessageFromToLinearLayout.setBackgroundDrawable(null);: "The method setBackgroundDrawable(Drawable) from the type View is deprecated"

And an error for subMessageFromToLinearLayout.setBackground(null);: "Call requires API level 16 (current min is 10): android.widget.LinearLayout#setBackground"

How can I fix this errors in order I can use both lines depending of the running Android version?

Thanks in advance.

Jorge Gil
  • 4,265
  • 5
  • 38
  • 57
  • have you set the target to 16+? The warning is a non-issue. I assume you can not build the project? – IAmGroot Apr 03 '13 at 22:06

2 Answers2

9

In general the most robust way makes use of class lazy loading:

static boolean isSDK17()
{
   return android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1;
}


if (isSDK17())
    xyMode_SDK17.setXyMode(context, mode);
else
    xyMode_SDK8.setXyMode(context, mode);


@TargetApi(17)
public class xyMode_SDK17
{
  static void setXyMode(Context context, boolean mode)
  {...}
}


public class xyMode_SDK8
{
  @SuppressWarnings("deprecation")
  static void setXyMode(Context context, boolean mode)
   {...}
}
j.holetzeck
  • 4,048
  • 2
  • 21
  • 29
  • Yes, I added the annotations `@TargetApi(Build.VERSION_CODES.JELLY_BEAN)`and `@SuppressWarnings("deprecation")`and that let me compile. Thanks! – Jorge Gil Apr 04 '13 at 20:36
1

Have you seen

ActionBarSherlock gives tons of "Call requires API level 11 (current min is 7)" errors

Android - set layout background programmatically

You can mark it with @TargetApi(16) and @SuppressWarnings("deprecated").

If the error still there, try cleaning the project or restart eclipse.

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

Community
  • 1
  • 1
pt2121
  • 11,720
  • 8
  • 52
  • 69