本文介绍了什么时候片段不附加到活动而只附加到上下文?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Fragment.getActivity() 的文档 它说: 返回当前与此片段关联的 FragmentActivity.如果片段与上下文相关联,则可能返回 null.

但是片段怎么能不与活动相关联呢?我的意思是,我不是总是需要一个 Activity 来在 Android 中显示任何内容吗?

But how can a fragment not be associated with an activity? I mean, don't I always need an activity to show anything in Android?

推荐答案

Fragment 不需要必须FragmentActivity 相关联.相反,它们实际上与 FragmentController,它碰巧代表您创建和管理 FragmentActivity,在创建、启动等托管活动时根据需要调用适当的调度方法.

Fragments are not required to be associated with a FragmentActivity. Instead, they are actually associated with a FragmentController, which FragmentActivity happens to create and manage on your behalf, calling the appropriate dispatch methods as necessary as the hosting activity is created, started, etc.

这种间接级别是 Facebook 的聊天头(显示由 Service 管理的 Window)如何能够重用相同的 FragmentFragmentActivity 使用的实例以及如何为 Android Automotive 构建导航应用(使用 CarAppService 来显示 Automotive 应用程序)还允许您重用 Fragments.

This level of indirection is how Facebook's Chat Heads (which displayed a Window managed by a Service) is able to reuse the same Fragment instances that a FragmentActivity uses and how building Navigation apps for Android Automotive (which use a CarAppService to display the Automotive app) allows you to also reuse Fragments.

当然,如果 您的 片段始终是从您的一个活动中创建的,那么,是的,您绝对可以假设 requireActivity() 将返回一个 FragmentActivity 任何时候 isAdded() 返回 true - 即在 onAttach()onDetach() 之间>.这确实包含在生命周期方法中,例如 onViewCreated() 或与您的 Fragment 的视图相关的任何内容(例如 OnClickListener).

Of course, if your Fragment is always created from within one of your Activities, then, yes, you can absolutely assume that requireActivity() will return a FragmentActivity anytime isAdded() returns true - i.e., between onAttach() and onDetach(). That does indeed include in lifecycle methods such as onViewCreated() or anything associated with your Fragment's views (such as an OnClickListener).

这篇关于什么时候片段不附加到活动而只附加到上下文?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-04 22:36