简体   繁体   English

Android/Java:片段实例化导致内存泄漏?

[英]Android/Java: Fragment instantiating causes memory leak?

My MainActivity has a Drawer and instantiates a new Fragment , depending on the clicked MenuItem (based on this tutorial ).我的MainActivity有一个Drawer并实例化一个新的Fragment ,具体取决于单击的MenuItem (基于本教程)。

I monitored the memory , which is slightly increasing on every Fragment change and I worry, that fragmentClass.newInstance() is not the right way.我监控了memory ,每次 Fragment 更改时都会略微增加,我担心fragmentClass.newInstance()不是正确的方法。

// MainActivity
public boolean onNavigationItemSelected(MenuItem item) {

    int id = item.getItemId();
    Fragment fragment = null;
    Class fragmentClass = null;
    if (id == R.id.nav_camera) {
        fragmentClass = CameraFragment.class;
    } else if (id == R.id.nav_gallery) {
        fragmentClass = GalleryFragment.class;
    } else if (id == R.id.nav_slideshow) {
        fragmentClass = SlideshowFragment.class;
    } else if (id == R.id.nav_manage) {
        fragmentClass = ManageFragment.class;
    } else if (id == R.id.nav_share) {
        fragmentClass = ShareFragment.class;
    } else if (id == R.id.nav_send) {
        fragmentClass = SendFragment.class;
    }

    try {
        fragment = (Fragment) fragmentClass.newInstance();
    } catch (Exception e) {
        e.printStackTrace();
    }

    FragmentManager fragmentManager = getSupportFragmentManager();
    fragmentManager.beginTransaction().replace(R.id.layout_main, fragment).commit();
}

I would expect something like:我希望是这样的:

// Pseudocode
if (fragmentManager.instanceExists(fragmentClass)) {
    // load instantiated fragment
} else {
    // newInstance()
}

How could I avoid memory leaks or is this even related?我怎样才能避免内存泄漏,或者这是否相关?

Thank you!谢谢!

Practically, there is no problems in that code.实际上,该代码没有问题。 Things you can optimize are:您可以优化的内容有:

  1. Reworking Fragment#instantiate() method (check docs )重做Fragment#instantiate()方法(检查文档
  2. Caching instances in something like Map in order not to create the new one every time you navigate through the drawerMap东西中缓存实例,以免每次浏览抽屉时都创建新的实例

Also, you can check if fragment exists in FragmentManager using FragmentManager#findFragmentById() or FragmentManager#findFragmentByTag()此外,您可以使用FragmentManager#findFragmentById()FragmentManager#findFragmentByTag()检查 FragmentManager 中是否存在片段

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM