Skip to content

Instantly share code, notes, and snippets.

@Takhion
Created June 3, 2015 09:33
Show Gist options
  • Save Takhion/7835b06f60f9c37b741a to your computer and use it in GitHub Desktop.
Save Takhion/7835b06f60f9c37b741a to your computer and use it in GitHub Desktop.
RecyclerView that calls onAttachedToWindow/onDetachedFromWindow on its adapter
public interface WindowAware {
public void onAttachedToWindow();
public void onDetachedFromWindow();
}
import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.util.AttributeSet;
public class WindowAwareRecyclerView extends RecyclerView {
private boolean attachedToWindow;
public WindowAwareRecyclerView(Context context) {
super(context);
}
public WindowAwareRecyclerView(Context context, AttributeSet attrs) {
super(context, attrs);
}
public WindowAwareRecyclerView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
@Override
public void setAdapter(Adapter adapter) {
final Adapter oldAdapter = getAdapter();
if (attachedToWindow && oldAdapter instanceof WindowAware) ((WindowAware)adapter).onDetachedFromWindow();
super.setAdapter(adapter);
if (attachedToWindow && adapter instanceof WindowAware) ((WindowAware)adapter).onAttachedToWindow();
}
@Override
protected void onAttachedToWindow() {
attachedToWindow = true;
super.onAttachedToWindow();
final Adapter adapter = getAdapter();
if (adapter instanceof WindowAware) ((WindowAware)adapter).onAttachedToWindow();
}
@Override
protected void onDetachedFromWindow() {
attachedToWindow = false;
super.onDetachedFromWindow();
final Adapter adapter = getAdapter();
if (adapter instanceof WindowAware) ((WindowAware)adapter).onDetachedFromWindow();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment