假设我有一个带有静态引用的父 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/