Android RecyclerView Snapping Effect Overriding fling method

I am trying to implement this method overriding the RecyclerView's Local Scrolling Center.

But I keep getting runtime error. Here is my code:

    public class custom_fling extends RecyclerView{
    private Point size = new Point();
    public custom_fling(Context context) {
        super(context);
    }

    @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 = (size.x - lastView.getWidth()) / 2;
        int rightMargin = (size.x - 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;
    }
}

      

I believe my problem is related to the casting of my RecyclerView. I am trying to apply it to custom_fling. Any ideas on how to resolve this?

+3


source to share





All Articles