2

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" />
Mohammad Jafar Mashhadi
  • 4,102
  • 3
  • 29
  • 49

2 Answers2

3

You can (and should) use setBackgroundResource with a reference to your background drawable resource. Available since API 1. As in:

this.setBackgroundResource(R.drawable.your_backround_resource_id);
Oren
  • 4,152
  • 3
  • 30
  • 37
  • I'm editing an open-source code that defined `updateBackground` function with this signature: `private void updateBackground(Drawable background)` so i don't have access to it's ID AFAIK. – Mohammad Jafar Mashhadi Aug 15 '14 at 10:51
  • in that case, CommonsWares answer is the way to go. compile your code against API 16 or higher. and live with the deprecation. note that API level 16 also introduces the [@targetAPI](http://stackoverflow.com/questions/11592820/writing-backwards-compatible-android-code) annotation, which you should use. – Oren Aug 15 '14 at 11:11
3

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.

CommonsWare
  • 986,068
  • 189
  • 2,389
  • 2,491
  • I'm using eclipse, in project properties window i have Android 4.4 with API Level=19 – Mohammad Jafar Mashhadi Aug 15 '14 at 16:06
  • @MJafarMash: OK, what is the exact compile error that you are getting? If it is complaining about your `minSdkVersion` being too low, you need to add the `@TargetApi()` annotation to the method that has your code snippet from your question. There's an Eclipse quick-fix (e.g., `Ctrl`-`1`) that should add that for you. – CommonsWare Aug 15 '14 at 16:21