Dyan Dyan - 1 month ago 17
Android Question

Switch fragments in view pager with flip animation

I've been trying to switch fragments inside a fragmentStatePagerAdapter, but even though I was able to change from fragment C-D in the same position; I have not been able to animate the transition.

I would appreciate any suggestions to achieve this effect:

A - B - C
| -> Flip transition back and forth
D

ABC or ABD have the normal animation transition, but when in C if I click a button I need to swap the fragment D with a flip animation and if I'm looking at D flip back to C.

Answer

The training documentation details how to create a card-flip animation. To implement this as you described, all you need to do is nest the last two fragments (the 'C' and 'D' fragments) of the ViewPager in a single fragment; then apply the animation to the transition:

public class CardFlipFragment extends Fragment {

    private boolean mShowingBack = false;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_card_flip, container, false);

        if(savedInstanceState == null) {
            getChildFragmentManager()
                    .beginTransaction()
                    .add(R.id.container, new FrontFragment())
                    .commit();
        }

        return view;
    }

    public void onFlip(View view) {
        if(mShowingBack) {
            getChildFragmentManager().popBackStack();
        } else {
            mShowingBack = true;

            getChildFragmentManager()
                    .setCustomAnimations(
                            R.animator.card_flip_right_in,
                            R.animator.card_flip_right_out,
                            R.animator.card_flip_left_in,
                            R.animator.card_flip_left_out)
                    .replace(R.id.container, new BackFragment())
                    .addToBackStack(null)
                    .commit();
        }
    }

}
Comments