Skip to content

Instantly share code, notes, and snippets.

@catvinhquang
Last active June 25, 2019 10:07
Show Gist options
  • Select an option

  • Save catvinhquang/40c345ffca5e569d8de1b3f7b4fa47b5 to your computer and use it in GitHub Desktop.

Select an option

Save catvinhquang/40c345ffca5e569d8de1b3f7b4fa47b5 to your computer and use it in GitHub Desktop.
Check out the video demo at the bottom
package catvinhquang.androiddeveloper;
import android.animation.ValueAnimator;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.support.annotation.Nullable;
import android.support.v7.widget.RecyclerView;
import android.util.AttributeSet;
import catvinhquang.androiddeveloper.Utils;
/**
* Created by Quang Cat on 25-Jun-2019
**/
public class IndicatorRecyclerView extends RecyclerView {
private int indicatorColor = 0xff0288D1;
private int indicatorHeight = Utils.dpToPx(2);
private int indicatorPosition = 0;
private int indicatorLeft;
private Paint paint;
private ValueAnimator animator;
public IndicatorRecyclerView(Context context) {
super(context);
init();
}
public IndicatorRecyclerView(Context context, @Nullable AttributeSet attrs) {
super(context, attrs);
init();
}
public IndicatorRecyclerView(Context context, @Nullable AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
init();
}
private void init() {
paint = new Paint(Paint.ANTI_ALIAS_FLAG);
paint.setColor(indicatorColor);
animator = new ValueAnimator();
animator.addUpdateListener(animation -> {
indicatorLeft = (int) animation.getAnimatedValue();
invalidate();
});
}
@Override
protected void dispatchDraw(Canvas canvas) {
super.dispatchDraw(canvas);
ViewHolder vh = findViewHolderForLayoutPosition(indicatorPosition);
if (vh != null) {
int l = animator.isRunning() ? indicatorLeft : vh.itemView.getLeft();
int t = getHeight() - indicatorHeight;
int r = l + vh.itemView.getWidth();
int b = getHeight();
canvas.drawRect(l, t, r, b, paint);
}
}
public void setIndicatorPosition(int position) {
if (indicatorPosition == position) {
return;
}
ViewHolder h1 = findViewHolderForLayoutPosition(indicatorPosition);
ViewHolder h2 = findViewHolderForLayoutPosition(position);
if (h1 != null && h2 != null) {
int start = h1.itemView.getLeft();
int end = h2.itemView.getLeft();
if (animator.isRunning()) {
animator.cancel();
}
animator.setIntValues(start, end);
animator.start();
}
indicatorPosition = position;
smoothScrollToPosition(position);
invalidate();
}
@Override
protected void onDetachedFromWindow() {
super.onDetachedFromWindow();
if (animator.isRunning()) {
animator.cancel();
}
}
}
@catvinhquang
Copy link
Author

demo

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment