Android Studio: false Lint warning forcing usage of "Compat" classes when high min SDK (25)
Asked Answered
C

1

7

I am working on a project with minSdkVersion set to 25 (aka Android 7.1).

Since this version is quite high, there are a lot of methods I can use without worrying about backward compatibility.

For example, retrieving a drawable, from a Fragment, should be as simple as:

context?.getDrawable(R.drawable.my_drawable)

In the source code, what it does is:

 return getResources().getDrawable(id, getTheme());

As far as I am concerned, such a method was introduced in API 21 (Android 5.0).

However, I get the following warning:

enter image description here

Looking at the source code of ContextCompat.getDrawable(...):

 if (Build.VERSION.SDK_INT >= 21) {
     return context.getDrawable(id);
 } else if (Build.VERSION.SDK_INT >= 16) {
     return context.getResources().getDrawable(id);
 } else { ... }

Since the min SDK is set to 25, the first if will always be called, which then the same code I have written. So why the warning?

I could suppress it with the @SuppressLint("UseCompatLoadingForDrawables") but it kinds of defeat the purpose... or I could follow it...

Is this normal? Should I really use ContextCompat and its affiliates or is there a setting somewhere to remove such a false warning?

PS: the project is also using Android X.

Chambers answered 3/12, 2020 at 10:24 Comment(1)
As an addition to this question: updated lint rules, namely UseCompatTextViewDrawableXml and UseAppTint, force to use compat app: attributes in xml which sounds like an overkill as well. Would be great to have a competent answer on that.Logicize
T
1

Ran into the same issue. I would say it is a false positive when you have a minSdk >= 21. Since as you say you will always enter the if branch which calls getDrawable.

So suppressing/ignoring it is the way to go until someone can make the lint rule smart enough to detect that you are on minSdkVersion higher than 21. You can ignore it globally by doing this in your build.gradle:

android { 
    ...
    lintOptions { 
        ignore("UseCompatLoadingForDrawables")
    }
}

Interestingly context.getColor(R.color.something) does not give a similar warning even though it has similar code in ContextCompat.getColor.

Talie answered 29/1, 2021 at 13:39 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.