gpt4 book ai didi

android - 什么时候应该使用 Fragment 中的 getActivity() 和 getContext()?

转载 作者:行者123 更新时间:2023-11-29 17:00:46 31 4
gpt4 key购买 nike

我想知道什么时候应该使用 Fragment 中的 getActivity() 和 getContext()?为什么不总是使用 getActivity。是否存在 getActivity 可能失败的情况?

最佳答案

不确定是否有 getActivityContext() 方法,但就 getContext()getActivity() 之间的区别而言,有真的不是你从电话中得到的类型。从源代码来看,v4 Fragment,它只是一个方便的方法,在返回之前将 Context 转换为 ActivityFragmentActivity ,它类似于正常的 Fragment 类。

/**
* Return the {@link Context} this fragment is currently associated with.
*/
public Context getContext() {
return mHost == null ? null : mHost.getContext();
}

/**
* Return the {@link FragmentActivity} this fragment is currently associated with.
* May return {@code null} if the fragment is associated with a {@link Context}
* instead.
*/
final public FragmentActivity getActivity() {
return mHost == null ? null : (FragmentActivity) mHost.getActivity();
}

此外,Activity 是一个 Context,因此没有太大区别。

关于android - 什么时候应该使用 Fragment 中的 getActivity() 和 getContext()?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43142738/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com