支持库中的Fragment的getContext和getActivity有什么区别? [英] What is different between getContext and getActivity from Fragment in support library?

查看:518
本文介绍了支持库中的Fragment的getContext和getActivity有什么区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

支持库中的Fragment中的getContext()getActivity()有什么区别?

What is different between getContext() and getActivity() from Fragment in support library?

它们是否总是返回相同的对象? (与当前片段相关的活动)

Do they always return the same object? (activity associated with current fragment)

推荐答案

在大多数情况下,没有区别但是 ...

In most cases there is no difference but ...

因此,最初Fragments托管在FragmentsActivity中,然后又得到了Context一个称为getActivity()的文件.

So originally Fragments were hosted in FragmentsActivity and back then to get Context one called getActivity().

只需检查源即可,并且Fragments现在可以由实现 FragmentHostCallback 接口.我认为这在支持库版本23中有所改变.

Just checked the sources and Fragments now can be hosted by anyone implementing FragmentHostCallback interface. And this changed in Support Library version 23, I think.

使用较新版本的支持库时,如果Fragment没有由Activity托管,则在调用getActivity()getContext()时可以得到不同的对象.

When using newer version of Support Library, when Fragment is not hosted by an Activity you can get different objects when calling getActivity() and getContext().

当您呼叫getActivity()时,您会得到一个Activity,它也是一个Context. 但是,当您呼叫getContext时,您会得到一个Context,它可能不是Activity.

When you call getActivity() you get an Activity which is a Context as well. But when you call getContext you will get a Context which might not be an Activity.

这篇关于支持库中的Fragment的getContext和getActivity有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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