Android - How to use different code lines depending of Android version

android, android-version

Solution

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)
   {...}
}

Problem

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.

Original source

Related problems