gpt4 book ai didi

Android fragment 内存泄漏

转载 作者:行者123 更新时间:2023-11-30 02:07:06 27 4
gpt4 key购买 nike

我的应用程序存在内存泄漏问题。我在第一个女巫中用 2 个 fragment 测试它我创建了一个大变量(ArrayList arr = new ArrayList(10000000);)以查看内存在更改 fragment 时是否为空(第二个为空),但不幸的是,这并没有发生。

Activity 是一个 ActionBarActivity,当我更改 fragment 时,我会执行 remove(fragment) 和 popbackstack,但每次更改时内存都会增加。

请帮帮我!!!

我在下面发布了一些代码:Activity 是 ActionBarActivity,它有一个侧边菜单 NavigationDrawer:

public class MainActivity extends ActionBarActivity implements NavigationDrawerCallbacks {
private Toolbar mToolbar;
private NavigationDrawerFragment mNavigationDrawerFragment;
private DrawerLayout mDrawerLayout;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mToolbar = (Toolbar) findViewById(R.id.toolbar_actionbar);
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer);
setSupportActionBar(mToolbar);
mNavigationDrawerFragment = (NavigationDrawerFragment) getFragmentManager().findFragmentById(R.id.fragment_drawer);
mNavigationDrawerFragment.setup(R.id.fragment_drawer, (DrawerLayout) findViewById(R.id.drawer), mToolbar);
setActionBarMenu(true);
selectItem(1);
}

private void selectItem(int position) {
final FragmentManager fm = getSupportFragmentManager();
FragmentTransaction ft = fm.beginTransaction();
for (int i = 0; i < fm.getBackStackEntryCount(); ++i) {
ft.remove(fm.findFragmentByTag(fm.getFragments().get(fm.getBackStackEntryCount() - 1).getTag()));
fm.popBackStack();
}
switch (position) {
case 0:
break;
case 1:
onChangeFragment(new UsersCheckInFragment(), false);
case 2:
etc...
}

ft.commit();
}

@Override
public void onNavigationDrawerItemSelected(int position) {
selectItem(position);
}

public void onChangeFragment(Fragment fragment, boolean addToBackStack) {
FragmentTransaction ft = getSupportFragmentManager().beginTransaction().replace(R.id.container, fragment, ((Object) fragment).getClass().getSimpleName());
if (addToBackStack)
ft.addToBackStack("");
ft.commit();
}
}

和 fragment :

public class UsersFragment extends Fragment {
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
final View view = inflater.inflate(R.layout.fragment_users, container, false);
mainActivity = (MainActivity) getActivity();
ArrayList<Integer> arr = new ArrayList<Integer>(10000000);
return view;
}
}

这里是一些内存屏幕

first fragment

second fragment

again first fragment

最佳答案

这不是内存泄漏,垃圾收集器最终会被系统调用。不要求系统在您完成处理后立即从内存中删除 fragment 。

关于Android fragment 内存泄漏,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30532426/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com