Skip to content

Instantly share code, notes, and snippets.

@tunjid
Created October 28, 2018 17:13
Show Gist options
  • Save tunjid/4871a029a30ad9b52156693bb5f081f1 to your computer and use it in GitHub Desktop.
Save tunjid/4871a029a30ad9b52156693bb5f081f1 to your computer and use it in GitHub Desktop.
private class Animator extends DataSetObserver implements OnPageChangeListener, OnAdapterChangeListener, OnGlobalLayoutListener {
private float lastPositionOffset;
private Animator() {
PagerAdapter adapter = viewPager.getAdapter();
if (adapter != null) adapter.registerDataSetObserver(this);
viewPager.addOnPageChangeListener(this);
viewPager.addOnAdapterChangeListener(this);
}
public void onAdapterChanged(@NonNull ViewPager viewPager, @Nullable PagerAdapter oldAdapter, @Nullable PagerAdapter newAdapter) {
if (newAdapter == null) return;
newAdapter.registerDataSetObserver(this);
buildIndicators(newAdapter);
}
public void onPageScrolled(int position, float fraction, int pixelOffset) {
float currentPositionOffset = ((float) position) + fraction;
boolean toTheRight = currentPositionOffset > lastPositionOffset;
onMoved(toTheRight, toTheRight ? position : position + 1, fraction);
lastPositionOffset = currentPositionOffset;
}
public void onGlobalLayout() {
ViewTreeObserver observer = guide.getViewTreeObserver();
if (observer.isAlive()) observer.removeOnGlobalLayoutListener(this);
guideLineWidth = guide.getWidth();
onMoved(false, viewPager.getCurrentItem() + 1, 0.0f);
}
private float getTranslation(boolean toTheRight, int originalPosition, float fraction) {
if (!toTheRight) fraction = 1.0f - fraction;
float chunkWidth = ((float) guideLineWidth) / requireNonNull(viewPager.getAdapter()).getCount();
float currentChunk = ((float) originalPosition) * chunkWidth;
float diff = chunkWidth * fraction;
return toTheRight ? currentChunk + diff : currentChunk - diff;
}
private void onMoved(boolean toTheRight, int position, float fraction) {
float translation = getTranslation(toTheRight, position, fraction);
indicator.setTranslationX(translation);
for (int i = watchers.size() - 1; i >= 0; i--) {
watchers.get(i).onIndicatorMoved(indicator, position, fraction, translation);
}
}
public void onPageSelected(int position) { }
public void onPageScrollStateChanged(int state) { }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment