Created
March 30, 2021 14:59
-
-
Save cesclong/50753a0a77cf6ad33c8bb5a99ebee333 to your computer and use it in GitHub Desktop.
响应生命周期Lifecycle的自定义RecyclerView
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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