Created
October 29, 2015 08:26
-
-
Save VAdaihiep/811711ae4644ff2bb76e to your computer and use it in GitHub Desktop.
SnappingRecyclerView horizontal in simplest way. Original version: http://stackoverflow.com/a/29171652/1393920
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
package vn.mog.mygimi.home; | |
import android.content.Context; | |
import android.support.v7.widget.LinearLayoutManager; | |
import android.support.v7.widget.RecyclerView; | |
import android.util.AttributeSet; | |
import android.util.Log; | |
import android.view.View; | |
public final class SnappingRecyclerView extends RecyclerView { | |
public SnappingRecyclerView(Context context) { | |
super(context); | |
} | |
public SnappingRecyclerView(Context context, AttributeSet attrs) { | |
super(context, attrs); | |
} | |
public SnappingRecyclerView(Context context, AttributeSet attrs, int defStyle) { | |
super(context, attrs, defStyle); | |
} | |
@Override | |
public boolean fling(int velocityX, int velocityY) { | |
LinearLayoutManager linearLayoutManager = (LinearLayoutManager) getLayoutManager(); | |
//these four variables identify the views you see on screen. | |
int lastVisibleView = linearLayoutManager.findLastVisibleItemPosition(); | |
int firstVisibleView = linearLayoutManager.findFirstVisibleItemPosition(); | |
View firstView = linearLayoutManager.findViewByPosition(firstVisibleView); | |
View lastView = linearLayoutManager.findViewByPosition(lastVisibleView); | |
//these variables get the distance you need to scroll in order to center your views. | |
//my views have variable sizes, so I need to calculate side margins separately. | |
//note the subtle difference in how right and left margins are calculated, as well as | |
//the resulting scroll distances. | |
int leftMargin = (getWidth() - lastView.getWidth()) / 2; | |
int rightMargin = (getWidth() - firstView.getWidth()) / 2 + firstView.getWidth(); | |
int leftEdge = lastView.getLeft(); | |
int rightEdge = firstView.getRight(); | |
int scrollDistanceLeft = leftEdge - leftMargin; | |
int scrollDistanceRight = rightMargin - rightEdge; | |
//if(user swipes to the left) | |
if (velocityX > 0) smoothScrollBy(scrollDistanceLeft, 0); | |
else smoothScrollBy(-scrollDistanceRight, 0); | |
return true; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment