本文介绍了SearchView内存泄漏的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我从SearchView菜单项
I am getting a memory leak from SearchView menu item
这是我的代码
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,泄漏将消失.我不明白这种泄漏会导致搜索主体为空,所以它怎么泄漏的?
if i comment out setting the setOnQueryTextListener the leak disappears. I don't understand this leak cause the body of the search is empty so how is it leaking?
推荐答案
从您的片段中,从onCreateOptionsMenu保存对searchItem MenuItem的引用,然后像上面这样简单地重写onDestroyOptionsMenu()并调用searchView.setOnQueryTextListener(null):
From your fragment, save a reference to your searchItem MenuItem from your onCreateOptionsMenu and then simply override onDestroyOptionsMenu() and call searchView.setOnQueryTextListener(null) like so:
// Set this in your onCreateOptionsMenu method
private MenuItem searchItem;
@Override
public void onDestroyOptionsMenu()
{
SearchView searchView = (SearchView) MenuItemCompat.getActionView(searchItem);
searchView.setOnQueryTextListener(null);
searchItem = null;
}
这篇关于SearchView内存泄漏的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!