Search code examples
javaandroidbackwards-compatibility

Backward compatible java code makes compile error


I'm new to android programming . I know some functions and classes were not in first android versions so we have to use different codes to work on different versions. For example to set a Button's background color i should use this code:

    // Set button background
    if (Build.VERSION.SDK_INT >= 16) {
        this.setBackground(background);
    } else {
        this.setBackgroundDrawable(background);
    }

My project's target API version is 11, so setBackground produces compile error and setBackgroundDrawable produces deprecation warning, how should i change this code or manifest or etc to make this app work on both versions?

In manifest:

<uses-sdk
    android:minSdkVersion="11"
    android:targetSdkVersion="19" />

Solution

  • If your backgrounds are resources, definitely follow Oren's answer. But let's assume that you have some other Drawable that you wish to use for your background.

    To clear up your compile error, you need to be compiling against API Level 16 or higher. In Eclipse, that is Project > Properties > Android from the main menu; in Android Studio, that is the compileSdkVersion value in your build.gradle file.

    You will have to live with the deprecation.