Android Support Library 27.1.0 new methods require

2019-03-28 08:21发布

According to the support library changelog and the Fragment class documentation (https://developer.android.com/reference/android/support/v4/app/Fragment.html), there are now new methods like requreActivity() and requireContext().

What is the purpose of these methods compared to getActivity() and getContext(), since they can still throw IllegalStateExceptions? Is this preferable to returning null when an activity or context cannot be found? And should I simply replace every getActivity() with requireActivity()?

1条回答
可以哭但决不认输i
2楼-- · 2019-03-28 08:53

It is basically to have a method that always returns a non null object or throw an exception. That is all.

From the docs:

Fragments now have requireContext(), requireActivity(), requireHost(), and requireFragmentManager() methods, which return a NonNull object of the equivalent get methods or throw an IllegalStateException.

https://developer.android.com/topic/libraries/support-library/revisions.html#27-1-0

This SO question also references the reasons behind this:

"The getActivity and getContext methods return nullable types because when the Fragment is not attached to an Activity, these methods already returned null. There's no change in behaviour, it's just explicitly marked now, so you can safely handle it."

https://stackoverflow.com/a/47253335/3268303

From reddit:

"I updated from support v26 to support v27, and had to add a bunch of !!s to activity/context methods in Fragments where I obviously don't expect it to be null. Nice to have require* methods that do this for me without the ugly !!s."

https://www.reddit.com/r/androiddev/comments/80ork8/support_library_2710_has_been_released/duxp75h/

查看更多
登录 后发表回答