SearchView内存泄漏

时间:2015-02-13 20:31:43

标签: android memory-leaks

我从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,则泄漏消失。我不明白这个泄漏导致搜索的主体是空的,所以它是如何泄漏的?

1 个答案:

答案 0 :(得分:2)

从您的片段中,从onCreateOptionsMenu中保存对searchItem MenuItem的引用,然后简单地覆盖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;
}