Android支持库27.1.0新方法requireActivity(),requireContext() [英] Android Support Library 27.1.0 new methods requireActivity(), requireContext()

查看:2649
本文介绍了Android支持库27.1.0新方法requireActivity(),requireContext()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

根据支持库changelog和Fragment类文档( https://developer.android.com/reference/android/support/v4/app/Fragment.html ),现在有诸如requreActivity()和requireContext()之类的新方法.

与getActivity()和getContext()相比,这些方法的目的是什么,因为它们仍然可以抛出IllegalStateExceptions?当找不到活动或上下文时,这是否比返回null更可取?我是否应该将每个getActivity()都替换为requireActivity()?

解决方案

基本上,有一种方法始终会返回非null对象或引发异常.就是这样.

从文档中

片段现在具有requireContext(),requireActivity(),requireHost()和requireFragmentManager()方法,它们返回等效的get方法的NonNull对象或抛出IllegalStateException.

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

此SO问题还引用了其背后的原因:

"getActivity和getContext方法返回可为null的类型,因为当Fragment未附加到Activity时,这些方法已经返回null.行为没有变化,现在已被明确标记,因此您可以安全地对其进行处理."/p>

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

来自reddit:

"我从支持v26更新为支持v27,并且不得不在Fragments的活动/上下文方法中添加一堆!! s,我显然不希望它为null.很高兴有require *方法可以这对我来说没有丑陋的!! s."

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

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()?

解决方案

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/

这篇关于Android支持库27.1.0新方法requireActivity(),requireContext()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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