使用片段时getContext()和requireContext()之间的区别 [英] Difference between getContext() and requireContext() when using fragments

查看:179
本文介绍了使用片段时getContext()和requireContext()之间的区别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

很长一段时间以来,我一直在怀疑这个问题,当我使用android片段并需要实例化Context时,或者需要将Context作为其他函数的参数传递时,我可以选择在使用getContext()和requireContext()方法可以实现这一点,我通常更喜欢使用requireContext(),但这仅仅是因为IDE(Android Studio)有时在我使用getContext()时会显示警告.不管我选择什么,看起来都是一样的.

I've been having this doubt since a long time, when I'm working with android fragments and I need to instantiate a Context, or I need to pass a Context as argument for other function, I can choose to use between getContext() and requireContext() methods to achieve that, I normally prefer to use requireContext(), but just because the IDE(Android Studio) shows warnings sometimes when I use the getContext().But the result of using one or other method seems to be the same, no matter what I choose.

我的问题是,这两种方法之间有什么区别吗?如果是这种情况,哪种情况更好,还是在每种情况下我都应该使用哪种呢?

My question is, is there any difference between these two methods? If this is the case, which one is better, or which should I use in each case?

推荐答案

getContext()返回可为空的 Context .

requireContext()返回一个非null的 Context ,或者当一个不可用时抛出异常.

requireContext() returns a nonnull Context, or throws an exception when one isn't available.

如果您的代码处于生命周期阶段,在此阶段您知道片段已附加到上下文,则只需使用 requireContext()来获取 Context 并保留静态分析器对潜在的NPE问题感到满意.

If your code is in a lifecycle phase where you know your fragment is attached to a context, just use requireContext() to get a Context and also keep static analyzers happy about potential NPE issues.

如果您的代码不在常规片段生命周期之内(例如,异步回调),则最好使用 getContext(),自己检查其返回值,然后再继续使用它.不为空.

If your code is outside of regular fragment lifecycle (say, an async callback), you might be better off using getContext(), checking its return value yourself and only proceeding using it if it was non-null.

在Kotlin中将其显式化为可空性更为重要,因为Kotlin已将其内置到语言的类型系统中.

Being explicit with nullability is even more important in Kotlin where it is built into the language's type system.

这篇关于使用片段时getContext()和requireContext()之间的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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