How to scale up Recycler View center item while scrolling in android?

后端 未结 4 1689
臣服心动
臣服心动 2020-12-16 05:41

I need to always highlight the center item in the recycler view while scrolling by scaling up.

4条回答
  •  情书的邮戳
    2020-12-16 05:42

    As an addendum to Mayank Garg's answer and the comments it has saying that it does not work for the first or last items, this happens when you are using this class and also adding extra padding to the list at the beginning and end in order for the first item to appear already centered. In these situations, functions like getDecoratedRight() and getDecoratedLeft() will include the extra padding in the sizes they return. This messes up the calculation of the view's midpoint, and hence it won't work for the first and last items.

    A solution to this is to detect if the layout manager is displaying the beginning of the list or not, and use a conditional to use a different calculation which uses one of the decorated anchors as origin but then uses the view's halved width in order to find the midpoint.

    In other words, in Mayank's code you have:

    childMidpoint =
       (getDecoratedRight(child) + getDecoratedLeft(child)) / 2.f;
    

    You can replace this with something similar to the following:

    if (findFirstVisibleItemPosition() == 0 && i == 0) {
       childMidPoint = getDecoratedRight(child) - child.getWidth() / 2.f;
    } else {
       childMidPoint = getDecoratedLeft(child) + child.getWidth() / 2.f;
    }
    

    In other words, this checks that the first child view is, or isn't, the first item in the adapter, and if so uses either the left or right decorated horizontal position to calculate the midpoint by subtracting or adding the item's halved width.

    Another simpler alternative is:

    childMidpoint = child.getX() + child.getWidth() / 2.0f
    

    But then again, you need to test if this fits other constraints you may have on your layout/views, since there is probably a reason Mayank used getDecoratedLeft() instead of getX().

提交回复
热议问题