简体   繁体   中英

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

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);

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM