Skip to content

Commit

Permalink
Unregister Data Observer from Adapter on clear method
Browse files Browse the repository at this point in the history
To avoid Memory Leaks.
  • Loading branch information
hugonardo committed Nov 8, 2017
1 parent bb6c006 commit a3227aa
Showing 1 changed file with 31 additions and 23 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,7 @@ public class EasyRecyclerView extends FrameLayout {
private int mProgressId;
private int mEmptyId;
private int mErrorId;
private final EasyDataObserver mEasyDataObserver = new EasyDataObserver(this);

public EasyRecyclerView(Context context) {
super(context);
Expand Down Expand Up @@ -226,15 +227,33 @@ public void setLayoutManager(RecyclerView.LayoutManager manager) {
mRecycler.setLayoutManager(manager);
}

/**
* @return the recycler adapter
*/
@Nullable
public RecyclerView.Adapter getAdapter() {
return mRecycler.getAdapter();
}

/**
* 设置适配器,关闭所有副view。展示recyclerView
* 适配器有更新,自动关闭所有副view。根据条数判断是否展示EmptyView
*
* @param adapter
*/
public void setAdapter(RecyclerView.Adapter adapter) {
setupAdapter(adapter);
showRecycler();
}

/**
* 设置适配器,关闭所有副view。展示进度条View
* 适配器有更新,自动关闭所有副view。根据条数判断是否展示EmptyView
*
* @param adapter
*/
public void setAdapterWithProgress(RecyclerView.Adapter adapter) {
mRecycler.setAdapter(adapter);
adapter.registerAdapterDataObserver(new EasyDataObserver(this));
setupAdapter(adapter);
//只有Adapter为空时才显示ProgressView
if (adapter instanceof RecyclerArrayAdapter){
if (((RecyclerArrayAdapter) adapter).getCount() == 0){
Expand All @@ -251,11 +270,20 @@ public void setAdapterWithProgress(RecyclerView.Adapter adapter) {
}
}

private void setupAdapter(RecyclerView.Adapter adapter) {
adapter.registerAdapterDataObserver(mEasyDataObserver);
mRecycler.setAdapter(adapter);
}

/**
* Remove the adapter from the recycler
*/
public void clear() {
mRecycler.setAdapter(null);
RecyclerView.Adapter adapter = mRecycler.getAdapter();
if (adapter != null) {
adapter.unregisterAdapterDataObserver(mEasyDataObserver);
mRecycler.setAdapter(null);
}
}

private void hideAll(){
Expand Down Expand Up @@ -413,26 +441,6 @@ public void removeOnItemTouchListener(RecyclerView.OnItemTouchListener listener)
mRecycler.removeOnItemTouchListener(listener);
}

/**
* @return the recycler adapter
*/
@Nullable
public RecyclerView.Adapter getAdapter() {
return mRecycler.getAdapter();
}

/**
* 设置适配器,关闭所有副view。展示recyclerView
* 适配器有更新,自动关闭所有副view。根据条数判断是否展示EmptyView
*
* @param adapter
*/
public void setAdapter(RecyclerView.Adapter adapter) {
mRecycler.setAdapter(adapter);
adapter.registerAdapterDataObserver(new EasyDataObserver(this));
showRecycler();
}

public void setOnTouchListener(OnTouchListener listener) {
mRecycler.setOnTouchListener(listener);
}
Expand Down

0 comments on commit a3227aa

Please sign in to comment.