如何抑制已弃用的 Android 功能的特定 Lint 警告?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/24208410/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-20 07:53:15  来源:igfitidea点击:

How to suppress specific Lint warning for deprecated Android function?

androidgradlelintdeprecation-warning

提问by JJD

I use a version switch to support older Android versions.

我使用版本开关来支持旧的 Android 版本。

int sdk = Build.VERSION.SDK_INT;
if (sdk < Build.VERSION_CODES.HONEYCOMB) {
    ColorDrawable colorDrawable = new ColorDrawable(shapeColor);
    //noinspection deprecation
    viewHolder.shape.setBackgroundDrawable(colorDrawable);
} else {
    viewHolder.shape.setColor(shapeColor);
}

When build the project with Gradle from the command linethe following warning is output by Lint:

从命令行使用 Gradle 构建项目时,Lint 会输出以下警告:

app/src/main/java/com/example/MyApp/CustomListAdapter.java:92: warning: 
[deprecation] setBackgroundDrawable(Drawable) in View has been deprecated
            viewHolder.shape.setBackgroundDrawable(colorDrawable);
                            ^

Can I annotate the specific line or method to mute the warning (since I do it on purpose)? I do notwant to disable allwarnings.

我可以注释特定的行或方法来使警告静音吗(因为我是故意这样做的)?我希望禁用所有警告。

回答by Ab?

Just something new: Not sure about Android Studio, but, to remove this warning from this line, you can use:

只是一些新东西:不确定 Android Studio,但是,要从此行中删除此警告,您可以使用:

//noinspection deprecation

This removes the warning from the next line. E.g:

这将删除下一行的警告。例如:

//noinspection deprecation
e.setBackgroundDrawable(editTextDrawable);

It won't show an error. However,as @JJD said, this still outputs the warning to the console. But at least you can have a nice error-less code which can be useful like for Git for example. And, this prevents the problem with @SupressWarnings, which is it ignores all warnings in the method. So if you have something deprecated that you are not aware of, @SupressWarningswill hide it and you will not be warned. That is the advantage of the //noinspection

它不会显示错误。但是,正如@JJD 所说,这仍然向控制台输出警告。但至少你可以有一个很好的无错误代码,它可以像 Git 一样有用。并且,这可以防止 出现问题@SupressWarnings,即忽略方法中的所有警告。因此,如果您有一些您不知道的弃用内容,请将其@SupressWarnings隐藏并且您不会收到警告。这就是它的优势//noinspection

回答by Martin Zeitler

I've noticed that the @SuppressLint("deprecated")inline annotation won't be picked up anymore - while @SuppressWarnings("deprecation")isbeing picked up.

我注意到@SuppressLint("deprecated")内联注释将不再被拾取 - 而@SuppressWarnings("deprecation")正在被拾取。

one can disable the Deprecationchecks for the Gradle linter with lintOptionswithin the module-level build.gradlefile; while there is no chance to define individual files like that:

可以在模块级文件中禁用对DeprecationGradle linter的检查;虽然没有机会像这样定义单个文件:lintOptionsbuild.gradle

android {
    lintOptions {
        disable 'Deprecation'
    }
}

oron can assign one rather detailed lint.xmlconfiguration file with LintOptions:lintConfig(when settings showAll true, it will still show the warnings - no matter the provided XML configuration):

或者on 可以lint.xml使用LintOptions:lintConfig分配一个相当详细的配置文件(设置时showAll true,它仍然会显示警告 - 无论提供的 XML 配置如何):

android {
    lintOptions {
        lintConfig file("lint.xml")
        showAll false
    }
}

where one can add individual files, by adding their paths:

可以通过添加路径来添加单个文件:

<?xml version="1.0" encoding="UTF-8"?>
<lint>
    <issue id="Deprecation" severity="Error">
        <ignore path="app/src/main/java/com/example/MyApp/CustomListAdapter.java" />
    </issue>
</lint>

The source code of com.android.builder.model.LintOptionsmight explain, what actually happens there (and confirms about 50% of what I've wrote).

的源代码com.android.builder.model.LintOptions可能会解释那里实际发生的事情(并确认了我所写内容的大约 50%)。

in order to get rid of the inline warnings in Android Studio... that linter appears to be another linter - and these annotations do not affect the linter of the Gradle build (it may be required to use this combined with one of the methods stated above, in order to ignore known deprecated classes and methods):

为了摆脱 Android Studio 中的内联警告......该 linter 似乎是另一个 linter - 这些注释不会影响 Gradle 构建的 linter(可能需要将其与所述方法之一结合使用上面,为了忽略已知的弃用类和方法):

//noinspection deprecation

updateThe Android Studio 2.3release notes mention a new feature:

更新Android Studio 2.3发行说明提到了一个新功能:

Lint Baseline: With Android Studio 2.3, you can set unresolved lint warnings as a baseline in your project. From that point forward, Lint will report only new issues. This is helpful if you have many legacy lint issues in your app, but just want to focus on fixing new issues. Learn more about Lint baseline and the new Lint checks & annotations added in this release.

Lint 基线:使用 Android Studio 2.3,您可以将未解决的 lint 警告设置为项目中的基线。从那时起,Lint 将仅报告新问题。如果您的应用程序中有许多遗留的 lint 问题,但只想专注于解决新问题,这会很有帮助。了解有关 Lint 基线以及此版本中添加的新 Lint 检查和注释的更多信息。

hereit's explained, how to create a Lint warnings baseline- which records the detected warnings into an XML file and then mutes them (which is way better than to have the code annotations inline, distributed all over the place); I'd assume, that options lintConfigand baselineshould be combine-able (depending on the requirements).

这里解释了如何创建 Lint 警告baseline- 将检测到的警告记录到 XML 文件中,然后将它们静音(这比内联代码注释更好,分布在各处);我会假设,即期权lintConfigbaseline应结合起来,能够(根据需要)。

android {
    lintOptions {
        baseline file("lint-baseline.xml")
    }
}

回答by user1

I ran into a similar problem. First I got a compiler warning:

我遇到了类似的问题。首先我收到一个编译器警告:

:compileDebugJava
Note: /path/file.java uses or overrides a deprecated API.
Note: Recompile with -Xlint:deprecation for details.

Which you can suppress with @SuppressWarnings("deprecation")or just ignore since it is a warning and does cause your build to fail. Additionally I got the lint error (details in build/lint-results.html):

您可以使用@SuppressWarnings("deprecation")它来抑制或忽略它,因为它是一个警告并且确实会导致您的构建失败。此外,我还收到了 lint 错误(详情见build/lint-results.html):

Call requires API level 13 (current min is 9)

This could be suppressed by adding @SuppressLint("NewApi"). Alternatively you could use @TargetApi(13)to hint that the method/class may use methods that depend on API version 13, rather than what you have set as minSdkVersion(e.g. 9).

这可以通过添加@SuppressLint("NewApi"). 或者,您可以使用@TargetApi(13)暗示方法/类可能使用依赖于 API 版本 13 的方法,而不是您设置的方法minSdkVersion(例如 9)。

The annotations can only be done at a class or function level, not for a single line. Also note that "deprecation" should not be capitalized, while that didn't seem to matter for "NewApi".

注释只能在类或函数级别完成,而不能在一行中完成。另请注意,“弃用”不应大写,而这对于“NewApi”似乎无关紧要。

回答by bestdayever

You need to create a lint.xml file to tell lint what to ignore.

您需要创建一个 lint.xml 文件来告诉 lint 要忽略什么。

http://tools.android.com/tips/lint/suppressing-lint-warningssee this for more details

http://tools.android.com/tips/lint/suppressing-lint-warnings查看更多详情

yours might look a little like this

你的可能看起来有点像这样

<?xml version="1.0" encoding="UTF-8"?>
<lint>
    <!-- Disable the given check in this project -->
    <issue id="Deprecation">
        <ignore path="app/src/main/java/com/example/MyApp/CustomListAdapter.java" />
    </issue>
</lint>

To handle this in the source you should use something like

要在源代码中处理此问题,您应该使用类似

 @SuppressLint("Deprecation")

回答by Codeversed

Case is important, use the following either inline or class-wide:

大小写很重要,使用以下内联或全类:

@Suppress("DEPRECATION")

This is in Kotlin.

这是在科特林。

回答by Blackd

To avoid lint warnings, always split functions so one function deals with the old system and other one deals with the new system. The old can supress the warning safely. The new one should be annotated to be used only on newest api levels.

为避免 lint 警告,请始终拆分函数,以便一个函数处理旧系统,另一个函数处理新系统。旧的可以安全地抑制警告。新的应该被注释为仅在最新的 api 级别上使用。

This is an example on how it should look:

这是一个关于它应该如何显示的示例:

    @SuppressWarnings("deprecation")
    private static int getVersionCode_old(@NonNull Context appContext) {
        PackageInfo pInfo;
        try {
            pInfo = appContext.getPackageManager().getPackageInfo(appContext.getPackageName(), 0);
            return pInfo.versionCode;
        } catch (Exception e) {
            e.printStackTrace();
            return 0;
        }
    }

    @RequiresApi(api = Build.VERSION_CODES.P)
    private static int getVersionCode_new(@NonNull Context appContext) {
        PackageInfo pInfo ;
        try {
            pInfo = appContext.getPackageManager().getPackageInfo(appContext.getPackageName(), 0);
            return (int) pInfo.getLongVersionCode();
        } catch (Exception e) {
            e.printStackTrace();
            return 0;
        }
    }

    public static int getVersionCodeUniversal(@NonNull Context appContext)
    {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
            return getVersionCode_new(appContext);
        }
        else
        {
            return getVersionCode_old(appContext);
        }
    }

Another important hint to avoid lint warnings: if you are using a whole deprecated class then you should remove all explicit imports for that class. Then just access to that class directly using its full path, and only do it in the old versions of your functions.

避免 lint 警告的另一个重要提示:如果您使用的是整个已弃用的类,那么您应该删除该类的所有显式导入。然后只需使用其完整路径直接访问该类,并且仅在旧版本的函数中执行此操作。

And finally, you should consider start using androidX, the new Google libraries where you will find a lot of universal functions ready to use. Then you can save a lot of time with this kind of small problems. For example, you can remove all the code of the above example and simply use this new and universal androidX function:

最后,您应该考虑开始使用 androidX,这是新的 Google 库,您可以在其中找到许多可以使用的通用功能。那么你可以在处理这种小问题时节省很多时间。例如,您可以删除上述示例的所有代码,只需使用这个新的通用 androidX 函数:

    PackageInfo.getLongVersionCode()

回答by Saeed Ghasemi

Just use @SuppressWarnings("deprecation")above the function to suppress that specific warning for that function only.

只需@SuppressWarnings("deprecation")在函数上方使用即可抑制该函数的特定警告。

Works like a charm!

奇迹般有效!

@Blackd has the better answer. You should accept that!

@Blackd 有更好的答案。你应该接受!

回答by hqzxzwb

Try to find a method from ViewCompatto replace the deprecated method.

尝试找到一种方法ViewCompat来替换已弃用的方法。

In your case, use ViewCompat.setBackground(View, Drawable).

在您的情况下,请使用ViewCompat.setBackground(View, Drawable).

There are many classes named XXXCompatfor cases like that, such as ContextCompat, ActivityCompatand so on.

有许多类以这样XXXCompat的情况命名,例如ContextCompatActivityCompat等等。