有关活动引用的Android Studio 3.0棉绒警告 [英] Android Studio 3.0 lint warnings for references to activity

查看:92
本文介绍了有关活动引用的Android Studio 3.0棉绒警告的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

将我的项目升级为使用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或其他过程中对其进行初始化来解决此问题,但这只会删除警告...

问题:

  1. 不是使用getActivity来指代Activity吗?什么是最佳做法?
  2. 这是我可以忽略的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:

  1. Is referring to the Activity using getActivity not the way to go? What is best practice?
  2. 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆