Android 支持库 27.1.0 新方法 requireActivity(), requireContext()
Android Support Library 27.1.0 new methods requireActivity(), requireContext()
根据支持库更改日志和 Fragment class 文档 (https://developer.android.com/reference/android/support/v4/app/Fragment.html),现在有像 requreActivity() 和 requireContext() 这样的新方法。
与 getActivity() 和 getContext() 相比,这些方法的目的是什么,因为它们仍然可以抛出 IllegalStateExceptions?当找不到 activity 或上下文时,这比返回 null 更可取吗?我应该简单地将每个 getActivity() 替换为 requireActivity() 吗?
基本上就是要有一个总是return非空对象或抛出异常的方法。仅此而已。
来自文档:
Fragments 现在有 requireContext()、requireActivity()、requireHost() 和 requireFragmentManager() 方法,其中 return 等效 get 方法的 NonNull 对象或抛出 IllegalStateException。
https://developer.android.com/topic/libraries/support-library/revisions.html#27-1-0
这个 SO 问题也引用了这背后的原因:
"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."
来自 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/
根据支持库更改日志和 Fragment class 文档 (https://developer.android.com/reference/android/support/v4/app/Fragment.html),现在有像 requreActivity() 和 requireContext() 这样的新方法。
与 getActivity() 和 getContext() 相比,这些方法的目的是什么,因为它们仍然可以抛出 IllegalStateExceptions?当找不到 activity 或上下文时,这比返回 null 更可取吗?我应该简单地将每个 getActivity() 替换为 requireActivity() 吗?
基本上就是要有一个总是return非空对象或抛出异常的方法。仅此而已。
来自文档:
Fragments 现在有 requireContext()、requireActivity()、requireHost() 和 requireFragmentManager() 方法,其中 return 等效 get 方法的 NonNull 对象或抛出 IllegalStateException。
https://developer.android.com/topic/libraries/support-library/revisions.html#27-1-0
这个 SO 问题也引用了这背后的原因:
"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."
来自 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/