memory-leaks - SearchView内存泄漏

  显示原文与译文双语对照的内容
0 0

我从SearchView菜单项中得到了内存泄漏

这是我的代码


 public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
 super.onCreateOptionsMenu(menu, inflater);
 if (hasSearchOption()) {
 MenuItem item = menu.findItem(R.id.action_search);
 if (item == null) {
 inflater.inflate(R.menu.search_menu, menu);
//Associate searchable configuration with the SearchView
 SearchManager searchManager =
 (SearchManager) Controller.getContext().getSystemService(Context.SEARCH_SERVICE);
 MenuItem searchItem = menu.findItem(R.id.action_search);
 SearchView searchView = (SearchView) MenuItemCompat.getActionView(searchItem);
 ComponentName cn = new ComponentName(getApplicationContext(), TestActivity.class);
 searchView.setSearchableInfo(
 searchManager.getSearchableInfo(cn));
 searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
 @Override
 public boolean onQueryTextSubmit(String s) {
//DO STUFF
 return false;
 }

 @Override
 public boolean onQueryTextChange(String s) {
 return false;
 }
 });
 }
 }
 }

类名


 | Ref. Objects | Shallow Heap | Ref. Shallow Heap | Retained Heap
-----------------------------------------------------------------------------------------------------------------------------------------------------------
mOnQueryChangeListener com.test.fragments.TestFragmentImpl$1 @ 0xa58ff9c0| 1 | 16 | 16 | 16
-----------------------------------------------------------------------------------------------------------------------------------------------------------

如果我注释出设置 setOnQueryTextListener,则泄漏消失。 我不明白这个漏洞导致搜索的body 是空的,所以它是如何泄漏的?

时间: 原作者:

0 0

从 fragment 中,将对 searchItem MenuItem的引用保存在onCreateOptionsMenu中,然后简单地重写 onDestroyOptionsMenu() 并调用 searchView.setOnQueryTextListener(null),如下所示:


//Set this in your onCreateOptionsMenu method

private MenuItem searchItem; 


@Override
public void onDestroyOptionsMenu()
{
 SearchView searchView = (SearchView) MenuItemCompat.getActionView(searchItem);
 searchView.setOnQueryTextListener(null);
 searchItem = null;
}

...