Skip to content

Instantly share code, notes, and snippets.

@cesclong
Created March 30, 2021 14:59
Show Gist options
  • Save cesclong/50753a0a77cf6ad33c8bb5a99ebee333 to your computer and use it in GitHub Desktop.
Save cesclong/50753a0a77cf6ad33c8bb5a99ebee333 to your computer and use it in GitHub Desktop.
响应生命周期Lifecycle的自定义RecyclerView
public class BaseRecyclerView extends RecyclerView implements LifecycleObserver {
public BaseRecyclerView(@NonNull Context context) {
super(context);
init(context);
}
public BaseRecyclerView(@NonNull Context context, @Nullable AttributeSet attrs) {
super(context, attrs);
init(context);
}
public BaseRecyclerView(@NonNull Context context, @Nullable AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
init(context);
}
private void init(Context context) {
if (context instanceof LifecycleOwner) {
((LifecycleOwner) context).getLifecycle().addObserver(this);
}
}
@OnLifecycleEvent(Lifecycle.Event.ON_DESTROY)
public void onDestory() {
/*
确保Adapter#onDetachedFromRecyclerView被调用
*/
setAdapter(null);
}
@Override
public void setLayoutManager(LayoutManager layoutManager) {
super.setLayoutManager(layoutManager);
if (layoutManager instanceof LinearLayoutManager) {
/*
确保Adapter#onViewDetachedFromWindow被调用
*/
((LinearLayoutManager) layoutManager).setRecycleChildrenOnDetach(true);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment