Leak canary, Recyclerview leaking mAdapter

前端 未结 4 1328
我寻月下人不归
我寻月下人不归 2021-01-30 16:33

I decided it was high time I learned how to use Leak Canary to detect Leaks within my apps, and as I always do, I tried to implement it in my project to really understand how to

4条回答
  •  逝去的感伤
    2021-01-30 17:37

    If the adapter lives any longer than the RecyclerView does, you've got to clear the adapter reference in onDestroyView:

    @Override
    public void onDestroyView() {
        recyclerView.setAdapter(null);
        super.onDestroyView();
    }
    

    Otherwise the adapter is going to hold a reference to the RecyclerView which should have already gone out of memory.

    If the screen is involved in transition animations, you actually have to take this one step further and only clear the adapter when the view has become detached:

    @Override
    public void onDestroyView() {
        recyclerView.addOnAttachStateChangeListener(new View.OnAttachStateChangeListener() {
            @Override
            public void onViewAttachedToWindow(View v) {
                // no-op
            }
    
            @Override
            public void onViewDetachedFromWindow(View v) {
                recyclerView.setAdapter(null);
            }
        });
        super.onDestroyView();
    }
    

提交回复
热议问题