android - 为什么 fragment 中的生命周期方法是公开的,而 Activity 的生命周期方法是 protected ?

标签 android android-fragments

根据 this link, Activity 受到保护以封装在框架包 android.app 和子类中。那么为什么 fragment 生命周期方法具有公共(public)访问修饰符?

最佳答案

简而言之,那是因为您的 Activity (不是您在内部)调用了 onCreateView() 等函数 或者在更抽象和推理的解释中,因为 Activity 可以包含 fragment 并用于 fragment Activity 通信。

需要公共(public)方法来访问功能,例如 findFragmentById()

一个 Activity 可以作为一个独立的实体存在。存在上下文,这是在 android 中执行与美国相关的操作的主要要求。 fragment 没有自己的上下文(getActivity() 方法在 fragment 中提供上下文)

来自 documentation

Though a Fragment's lifecycle is tied to its owning activity, it has its own wrinkle on the standard activity lifecycle. It includes basic activity lifecycle methods such as onResume(), but also important are methods related to interactions with the activity and UI generation.

编辑:按照与您链接的答案类似的方法, fragment (为了向后兼容)也显示为 android.support.v4.app.Fragment .但是Activity类只存在于android.app中,所以为了保证向后兼容,在这种情况下public methods都是存在的

关于android - 为什么 fragment 中的生命周期方法是公开的,而 Activity 的生命周期方法是 protected ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28613855/

相关文章:

java - 渐变 : not installed (cordova requirements)

Android GUI XML 与代码

Android - 在不保存的情况下发送前调整大小和裁剪图片

java - 如何在 PageViewer 中显示 3 个 fragment

android - 如何在 RelativeLayout 中找到导致循环依赖的原因

android - fragment 中不合适的上下文菜单

android - 当关闭对话框 fragment 时,无法在 onSaveInstanceState 之后执行此操作

java - 在 fragment 之间使用 Otto 传递字符串

android - 如何在 fragment 之间导航时消除白色闪烁/闪光?

android - 在 Android 中使用 ScrollView 的图表