View translation in sliding a ViewPager

前端 未结 4 1141
猫巷女王i
猫巷女王i 2021-02-13 11:26

I was reading an example on customizing ViewPager\'s sliding page animation that entails translating the page(View) to a certain amount. The example is

4条回答
  •  野趣味
    野趣味 (楼主)
    2021-02-13 11:54

    There is one thing you are missing here, the PageTransformer is applied to the views AFTER they have been positioned.

    So, with or without a PageTransformer attached to the PageView - when you scroll between pages - you simply doing a scroll (like in a LiseView) with SNAP capabilities.

    The PageTransformer only adds effects on top of that.

    So the purpose of,

    float vertMargin = pageHeight * (1 - scaleFactor) / 2;
    float horzMargin = pageWidth * (1 - scaleFactor) / 2;
    if (position < 0) {
        view.setTranslationX(horzMargin - vertMargin / 2);
    } else {
        view.setTranslationX(-horzMargin + vertMargin / 2);
    }
    

    is NOT to move the pages - but to compensate the page shrinking.

    Without it, the page will have some ugly side effects. TRY IT, remove the lines :) - The views will go right/left but the positioning will be off.

    So, the translation X does not move the page, but, in this case, simply manages the pages spacing to improve the animation feel - the above is the Math for it. What it does is to reduce the space between the pages based on the screen height/width. First it negates the space (horzMargin) then it adds a little spacing (- vertMargin / 2)

    And that is why your calculation is not good (w*x) - You are trying to move the page - But it is already moving.

提交回复
热议问题