Cube Flip animation for Fragments on Android

2019-04-08 16:05发布

问题:

I want to implement a basic 3d cube and rotate it by 90degrees either horizontally or vertically on Touch. What i want to implement is something similar to what is shown in the image below.

I've achieved this using ViewPager's ViewTransformer But I am not happy with the result. The animation is not very smooth, and i cannot flip it, i have to drag my finger across the entire widht of the screen to rotate the cube. I want to just flip it, but am not able to achieve it.

I've used BTGridPager-Android to achieve the above. But as mentioned, its not very convincing.

Here is my ViewTransformer code:

    public abstract class ABaseTransformer implements PageTransformer {
 @Override
 public void transformPage(View page, float position) {
  onPreTransform(page, position);
  onTransform(page, position);
  onPostTransform(page, position);
 }
protected void onPreTransform(View page, float position) {
  final float width = page.getWidth();

  page.setRotationX(0);
  page.setRotationY(0);
  page.setRotation(0);
  page.setScaleX(1);
  page.setScaleY(1);
  page.setPivotX(0);
  page.setPivotY(0);
  page.setTranslationY(0);
  page.setTranslationX(isPagingEnabled() ? 0f : -width * position);

  if (hideOffscreenPages()) {
   page.setAlpha(position <= -1f || position >= 1f ? 0f : 1f);
  } else {
   page.setAlpha(1f);
  }
 }


public class HorizontalCubeOutTransformer extends ABaseTransformer {

 @Override
 protected void onTransform(View view, float position) {

  final float normalizedposition = Math.abs(1 - Math.abs(position));

  view.setPivotX(position < 0f ? view.getWidth() : 0f);
  view.setPivotY(view.getHeight() * 0.5f);
  view.setRotationY(90f * position);
  view.setAlpha(normalizedposition);
 }

 @Override
 public boolean isPagingEnabled() {
  return true;
 }

}



public class VerticalCubeOutTransformer extends ABaseTransformer {


 @Override
 protected void onTransform(View view, float position) {

  final float normalizedposition = Math.abs(Math.abs(position) - 1);
  view.setAlpha(normalizedposition);
  view.setTranslationX(view.getWidth() * -position);
  view.setTranslationY(position * view.getHeight());

  view.setPivotX(view.getWidth() * 0.5f);
  view.setPivotY(position < 0f ? view.getHeight() : 0f);
  view.setRotationX(90f * -position);

 }

 @Override
 public boolean isPagingEnabled() {
  return false;
 }
}

What I would like to know is how to rotate the cube on the flip gesture. Note: I would like to achieve this without OpenGL or SurfaceView.

UPDATE: till now i have implemented the cube flip using fragmenttransactionExtended but now i got some other problem, as the current fragment disappears as soon as the flip begins

回答1:

You can use FragmentTransactionExtended

FragmentTransactionExtended

it provides all types of animations between frgaments