如何在Android Studio中正确导入NonNull注释?

3
我想在我的Handler文件中使用NonNull、Nullable和UnsopportedAppUsage的注释,但是第2、3和4行给了我一个错误。我该如何解决?
package android.os;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.annotation.UnsupportedAppUsage;
import android.util.Log;
import android.util.Printer;
2个回答

4
答案有两个方面。对于@NonNull@Nullable,请按照以下步骤进行操作:
如果您使用的是androidx,请添加
implementation 'androidx.annotation:annotation:1.0.2'

如果您使用的是旧版支持库(您的导入是针对此版本的),或者
implementation 'com.android.support:support-annotations:28.0.0'

build.gradle文件中添加到您的依赖项中。 版本号可能对您而言有所不同。

请注意,还有android.annotation.Nullable类,但它是Android操作系统的内部API(如果使用会导致构建错误)。

对于@UnsupportedAppUsage: 此注释表示Android SDK内部的某些内容实际上正在使用,但不应该使用。在您的代码中使用此注释没有太多意义。此外,该注释在SDK中是隐藏的,您无法使用它。


1
在你的 app/build.gradle 文件中:
dependencies {
    implementation 'androidx.appcompat:appcompat:1.2.0'
}

在你的Java类中:
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

然后你可以在你的字段/变量中使用@NonNull,就像这样:
@NonNull
public final JSONObject content;

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接