有关活动引用的Android Studio 3.0棉绒警告 [英] Android Studio 3.0 lint warnings for references to activity
问题描述
将我的项目升级为使用API级别为27.0.0(Android 8.1)的Android Studio 3.0之后,我收到了很多与片段中使用getActivity()有关的新棉绒警告(我认为这很正常). /p>
示例:
((AppCompatActivity) getActivity()).setSupportActionBar(toolbar);
getActivity().getMenuInflater().inflate(R.menu.pavingreport_dialog_menu, menu);
两个示例都抱怨存在null异常.
示例:
Method invocation 'getMenuInflater' may produce 'java.lang.NullPointerException'
我知道我可以通过将活动添加为字段并在onCreate或其他过程中对其进行初始化来解决此问题,但这只会删除警告...
问题:
- 不是使用getActivity来指代Activity吗?什么是最佳做法?
- 这是我可以忽略的AS中的错误"吗?
Fragment
中的
getActivity()
获得了带有支持库27.0.0的@Nullable
批注.感谢杰克.这意味着它现在可以按预期运行,因为它可以返回null.
After upgrading my project to use Android Studio 3.0 with API level 27.0.0 (Android 8.1) I get a lot of new lint warnings related to using getActivity() inside a fragment (which I thought was perfectly all right).
Examples:
((AppCompatActivity) getActivity()).setSupportActionBar(toolbar);
getActivity().getMenuInflater().inflate(R.menu.pavingreport_dialog_menu, menu);
Both examples complains about null exceptions.
Example:
Method invocation 'getMenuInflater' may produce 'java.lang.NullPointerException'
I know I can fix this by adding activity as a field and initialize it during onCreate or something, but this only removes the warning...
Questions:
- Is referring to the Activity using getActivity not the way to go? What is best practice?
- Is this a 'bug' in AS that I can ignore?
getActivity()
in Fragment
got the @Nullable
annotation with support libraries 27.0.0. Thanks to Jake. Meaning this is now working as expected since it can return null.
这篇关于有关活动引用的Android Studio 3.0棉绒警告的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!