Skip to content

Instantly share code, notes, and snippets.

@samuel22gj
Last active January 30, 2018 08:23
Show Gist options
  • Save samuel22gj/913f3414350277f10854eb892f6429d8 to your computer and use it in GitHub Desktop.
Save samuel22gj/913f3414350277f10854eb892f6429d8 to your computer and use it in GitHub Desktop.
A RecyclerView that make the first ViewHolder has parallax effect.
<?xml version="1.0" encoding="utf-8"?>
<resources>
<declare-styleable name="ParallaxRecyclerView">
<attr name="parallaxMultiplier" format="float"/>
</declare-styleable>
</resources>
/**
* Make the first {@link RecyclerView.ViewHolder} has parallax effect.
*/
public class ParallaxRecyclerView extends ECRecyclerView {
private static final String TAG = ParallaxRecyclerView.class.getSimpleName();
private static final float DEFAULT_PARALLAX_MULTIPLIER = 0.5f;
private float mParallaxMultiplier = DEFAULT_PARALLAX_MULTIPLIER;
private OnParallaxScrollListener mParallaxScrollListener;
private int mPreviousVerticalScrollOffset;
public ParallaxRecyclerView(Context context) {
this(context, null);
}
public ParallaxRecyclerView(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public ParallaxRecyclerView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
init(context, attrs, defStyle);
}
private void init(Context context, AttributeSet attrs, int defStyle) {
TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.ParallaxRecyclerView, defStyle, 0);
mParallaxMultiplier = typedArray.getFloat(R.styleable.ParallaxRecyclerView_parallaxMultiplier, DEFAULT_PARALLAX_MULTIPLIER);
typedArray.recycle();
addOnScrollListener(new OnScrollListener() {
@Override
public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
int verticalScrollOffset = recyclerView.computeVerticalScrollOffset();
if (verticalScrollOffset != mPreviousVerticalScrollOffset) {
mPreviousVerticalScrollOffset = verticalScrollOffset;
RecyclerView.ViewHolder viewHolder = recyclerView.findViewHolderForAdapterPosition(0);
if (viewHolder != null && viewHolder.itemView != null && mParallaxMultiplier != 0.0f) {
View view = viewHolder.itemView;
view.setTranslationY(verticalScrollOffset * mParallaxMultiplier);
if (mParallaxScrollListener != null) {
int viewHeight = view.getMeasuredHeight();
mParallaxScrollListener.onParallaxChange(viewHeight, verticalScrollOffset);
}
}
}
}
});
}
public void setPrallaxMultiplier(float parallaxMultiplier) {
mParallaxMultiplier = parallaxMultiplier;
}
public float getParallaxMultiplier() {
return mParallaxMultiplier;
}
public void setParallaxScrollListener(OnParallaxScrollListener listener) {
mParallaxScrollListener = listener;
}
public interface OnParallaxScrollListener {
void onParallaxChange(int viewHeight, int scrollOffset);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment