问题
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?
回答1:
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.
来源:https://stackoverflow.com/questions/47138807/android-studio-3-0-lint-warnings-for-references-to-activity