java - 对家长 Activity 使用静态有什么问题?

标签 java android static

假设我有一个带有静态引用的父 Activity ParentHost:

   ParentHost extends FragmentActivity {
   static ParentHost parent_host;
   static ViewPager pager;

现在让我们使用如下引用:

public class TestPage extends Fragment {   
            button.setOnClickListener(new  View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    //What's wrong with this?
                    ParentHost.pager.setCurrentItem(1);
                    or:
                    ParentHost.parent_host.finish();
                }
            });

我试过破坏我的应用程序(启动、暂停、杀死 RAM),但我没有发现任何问题。

这个方法适合家长 Activity 吗?

对于 future 的读者:

切换到 ((ParentHost) getActivity()).whatever() 是使用运行类实例的适当方式。来自 Gabe 的评论:

The reason its safe is its held in an instance variable and not in a static. Thus even though there's always 1 reference to it the GC can tell that the only reference to it is held by one of its children and that the whole chain can be GCed (the ability to do this is why java uses a mark and sweep style GC instead of a reference count)

最佳答案

好吧,你不需要它。 fragment 可以通过调用 getActivity() 来获取其 Activity 。

此外,它是一个内存泄漏。如果 fragment 对其 Activity 有静态引用,则该 Activity 将永远不会被清除。这意味着它持有的任何物体都不会被清理。这意味着它的所有 View 、位图和内存结构,它们只会耗尽您的 RAM。

所以这是一个非常糟糕的主意,并且不会给您带来任何好处。为什么要这样做?

关于java - 对家长 Activity 使用静态有什么问题?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29179648/

相关文章:

javascript - 函数作为 react 子项无效? - 需要帮助将获取的数据提取到表中

java - 如何将字符串流转换为字符串流对?

android - 如何在 Android Studio 2.3 中启用注解处理器

java - 使用多个标记创建折线

c++ - 无法在Qt中调用静态方法

java - 如何在运行时使用 Webdriver 中的 java (jxl) 在现有 excel 文件中添加新的 excel 工作表

java - 错误 : Could not find or load main class C:\Program Files\Java\jdk1. 7.0_25\jre\bin\java

android - 将服务从一个 Activity 传递到另一个 Activity

PHP 单例和继承

c# - 在静态类中声明的对象何时会被垃圾回收?