Created
June 3, 2015 09:33
-
-
Save Takhion/7835b06f60f9c37b741a to your computer and use it in GitHub Desktop.
RecyclerView that calls onAttachedToWindow/onDetachedFromWindow on its adapter
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 interface WindowAware { | |
public void onAttachedToWindow(); | |
public void onDetachedFromWindow(); | |
} |
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
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