com.clemot.julian.easylib.EasyActivity.java Source code

Java tutorial

Introduction

Here is the source code for com.clemot.julian.easylib.EasyActivity.java

Source

package com.clemot.julian.easylib;

/*
Copyright 2015 Julian Clemot
    
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
    
http://www.apache.org/licenses/LICENSE-2.0
    
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
 */

import android.os.Build;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.util.Pair;
import android.support.v4.view.ViewCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.transition.Transition;
import android.transition.TransitionInflater;
import android.util.Log;
import android.view.View;

import java.util.Iterator;
import java.util.List;

/**
 * Created by julianclemot on 15/04/15.
 */
public class EasyActivity extends AppCompatActivity {

    public enum FragmentCustomAnimation {
        PUSH_LEFT, PUSH_RIGHT, POP, EXPLODE;
    }

    // FragmentActivity Cycle Life
    // Used only for back stack
    private FragmentManager fragmentManager;

    /**
     * Public constructor
     */
    public EasyActivity() {
        super();
        fragmentManager = this.getSupportFragmentManager();
    }

    /**
     * Test if fragment is already loaded
     *
     * @param tag name
     * @return true or false
     */
    public boolean fragmentIsAlreadyLoaded(String tag) {
        if (fragmentManager.findFragmentByTag(tag) == null) {
            return false;
        } else {
            return true;
        }
    }

    public Fragment getVisibleFragment() {
        FragmentManager fragmentManager = this.getSupportFragmentManager();
        List<Fragment> fragments = fragmentManager.getFragments();
        int size = fragments.size();
        for (int i = (size - 1); i > 0; i--) {
            Fragment fragment = fragments.get(i);
            if (fragment != null && fragment.isVisible())
                return fragment;
        }
        return null;
    }

    /**
     * Is set to null by default, override it if you want to use a navigation Drawer
     *
     * @return the drawerLayout used for the NavigationDrawer
     */
    public DrawerLayout getDrawerLayout() {
        return null;
    }

    /**
     * Is set to null by default, override it if you want to use a navigation Drawer
     *
     * @return the ActionBarDrawerToggle used for the NavigationDrawer
     */
    public ActionBarDrawerToggle getDrawerToggle() {
        return null;
    }

    public FragmentTransaction addTransitions(FragmentTransaction fragmentTransaction, Fragment currentFragment,
            final Fragment nextFragment, Pair<View, String>... sharedElements) {
        if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {

            // Set shared and scene transitions

            //setSharedElementReturnTransition(TransitionInflater.from(getActivity()).inflateTransition(R.transition.trans_move));
            //setExitTransition(TransitionInflater.from(getActivity()).inflateTransition(android.R.transition.explode));

            //Exit Transition for the current Fragment
            currentFragment
                    .setExitTransition(TransitionInflater.from(this).inflateTransition(R.transition.trans_move));

            //ReEnter Transition for the current Fragment
            currentFragment
                    .setReenterTransition(TransitionInflater.from(this).inflateTransition(R.transition.trans_move));

            nextFragment.setSharedElementReturnTransition(
                    TransitionInflater.from(this).inflateTransition(R.transition.trans_move));
            // Set shared and scene transitions on 2nd fragment
            nextFragment.setSharedElementEnterTransition(
                    TransitionInflater.from(this).inflateTransition(R.transition.trans_move));

            Transition transition = TransitionInflater.from(this).inflateTransition(android.R.transition.explode);
            transition.addListener(new Transition.TransitionListener() {
                @Override
                public void onTransitionStart(Transition transition) {
                    ((EasyFragment) nextFragment).onTransitionStart(transition);
                }

                @Override
                public void onTransitionEnd(Transition transition) {
                    ((EasyFragment) nextFragment).onTransitionEnd(transition);
                }

                @Override
                public void onTransitionCancel(Transition transition) {
                    ((EasyFragment) nextFragment).onTransitionEnd(transition);
                }

                @Override
                public void onTransitionPause(Transition transition) {
                    ((EasyFragment) nextFragment).onTransitionPause(transition);
                }

                @Override
                public void onTransitionResume(Transition transition) {
                    ((EasyFragment) nextFragment).onTransitionResume(transition);
                }
            });
            nextFragment.setEnterTransition(transition);

            //Return Transition for the next Fragment
            nextFragment.setReturnTransition(
                    TransitionInflater.from(this).inflateTransition(android.R.transition.explode));

            for (int i = 0; i < sharedElements.length; i++) {
                ViewCompat.setTransitionName(sharedElements[i].first, sharedElements[i].second);
                fragmentTransaction.addSharedElement(sharedElements[i].first, sharedElements[i].second);
            }
        }
        return fragmentTransaction;
    }

    /**
     * Add Fragment
     *
     * @param lastFrag  fragment
     * @param frag      fragment
     * @param id        which child is loaded
     * @param backStack back stack or not
     */
    public void addFragment(Fragment lastFrag, Fragment frag, int id, boolean backStack) {
        FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
        fragmentTransaction.add(id, frag, frag.getClass().getName());
        // An optional name for this back stack state, or null.
        if (backStack) {
            fragmentTransaction.addToBackStack(null);
        }
        fragmentTransaction.commit();

        try {
            fragmentManager.executePendingTransactions();
        } catch (IllegalStateException iSe) {

            Log.e("MultiFrag", "Handle crash:" + iSe.getStackTrace());
        }
    }

    public void replaceFragment(Fragment lastFrag, final Fragment frag, int id, boolean backStack,
            Pair<View, String>... sharedElements) {

        FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();

        fragmentTransaction.replace(id, frag, frag.getClass().getName());
        // An optional name for this back stack state, or null.
        if (backStack) {
            fragmentTransaction.addToBackStack(null);
        }

        fragmentTransaction = addTransitions(fragmentTransaction, lastFrag, frag, sharedElements);

        fragmentTransaction.commit();

        try {
            fragmentManager.executePendingTransactions();
        } catch (IllegalStateException iSe) {
            Log.e("MultiFrag", "Handle crash:" + iSe.getStackTrace());
            iSe.printStackTrace();
        }
    }

    /**
     * Add fragment with transition animation
     *
     * @param lastFrag  fragment
     * @param frag      fragment
     * @param id        which child is loaded
     * @param animation (POP/PUSH LEFT/PUSH RIGHT)
     * @param backStack back stack or not
     */
    public void addFragment(Fragment lastFrag, Fragment frag, int id, FragmentCustomAnimation animation,
            boolean backStack) {
        FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
        addCustomAnimation(fragmentTransaction, animation);
        fragmentTransaction.add(id, frag, frag.getClass().getName());
        // An optional name for this back stack state, or null.
        if (backStack) {
            fragmentTransaction.addToBackStack(null);
        }
        fragmentTransaction.commit();
        try {
            fragmentManager.executePendingTransactions();
        } catch (IllegalStateException iSe) {
            Log.e("MultiFrag", "Handle crash:" + iSe.getStackTrace());
        }
    }

    /**
     * Add Fragment with transition animation
     *
     * @param lastFrag    fragment
     * @param frag        fragment
     * @param id          which child is loaded
     * @param transitMode mode
     * @param backStack   back stack or not
     */
    public void addFragment(Fragment lastFrag, Fragment frag, int id, int transitMode, boolean backStack) {
        FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
        fragmentTransaction.setTransition(transitMode);
        fragmentTransaction.add(id, frag, frag.getClass().getName());
        // An optional name for this back stack state, or null.
        if (backStack) {
            fragmentTransaction.addToBackStack(null);
        }
        fragmentTransaction.commit();
        try {
            fragmentManager.executePendingTransactions();
        } catch (IllegalStateException iSe) {
            Log.e("MultiFrag", "Handle crash:" + iSe.getStackTrace());
        }
    }

    /**
     * Show Fragment
     *
     * @param lastFrag fragment
     * @param frag     fragment
     */
    public void showFragment(Fragment lastFrag, Fragment frag) {
        FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
        fragmentTransaction.show(frag);
        fragmentTransaction.commit();
        fragmentManager.executePendingTransactions();
    }

    /**
     * Show fragment with transition animation
     *
     * @param lastFrag    fragment
     * @param frag        fragment
     * @param transitMode mode
     */
    public void showFragment(Fragment lastFrag, Fragment frag, int transitMode) {
        FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
        fragmentTransaction.setTransition(transitMode);

        fragmentTransaction.show(frag);
        fragmentTransaction.commit();
        fragmentManager.executePendingTransactions();
    }

    /**
     * Show fragment with transition animation
     *
     * @param lastFrag  fragment
     * @param frag      fragment
     * @param animation (POP/PUSH LEFT/PUSH RIGHT)
     */
    public void showFragment(Fragment lastFrag, Fragment frag, FragmentCustomAnimation animation) {
        FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
        addCustomAnimation(fragmentTransaction, animation);
        fragmentTransaction.show(frag);
        fragmentTransaction.commit();
        fragmentManager.executePendingTransactions();
    }

    /**
     * Replace fragment
     *
     * @param lastFrag fragment
     * @param frag     fragment
     * @param id       which child is loaded
     */
    public void replaceFragment(Fragment lastFrag, Fragment frag, int id) {
        FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
        fragmentTransaction.replace(id, frag);
        fragmentTransaction.commit();
        fragmentManager.executePendingTransactions();
    }

    /**
     * Replace fragment with transition animation
     *
     * @param lastFrag    fragment
     * @param frag        fragment
     * @param id          which child is loaded
     * @param transitMode mode
     */
    public void replaceFragment(Fragment lastFrag, Fragment frag, int id, int transitMode) {
        FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
        fragmentTransaction.setTransition(transitMode);
        fragmentTransaction.replace(id, frag);
        fragmentTransaction.commit();
        fragmentManager.executePendingTransactions();
    }

    /**
     * Replace fragment with transition animation
     *
     * @param lastFrag  fragment
     * @param frag      fragment
     * @param id        which child is loaded
     * @param animation (POP/PUSH LEFT/PUSH RIGHT)
     */
    public void replaceFragment(Fragment lastFrag, Fragment frag, int id, FragmentCustomAnimation animation) {
        FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
        addCustomAnimation(fragmentTransaction, animation);
        fragmentTransaction.replace(id, frag);
        fragmentTransaction.commit();
        fragmentManager.executePendingTransactions();
    }

    /**
     * Replace fragment
     *
     * @param lastFrag fragment
     * @param frag     fragment
     */
    public void attachFragment(Fragment lastFrag, Fragment frag) {
        FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
        fragmentTransaction.attach(frag);
        fragmentTransaction.commit();
        fragmentManager.executePendingTransactions();
    }

    /**
     * Detach fragment
     *
     * @param lastFrag fragment
     * @param frag     fragment
     */
    public void detachFragment(Fragment lastFrag, Fragment frag) {
        FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
        fragmentTransaction.detach(frag);
        fragmentTransaction.commit();
        fragmentManager.executePendingTransactions();
    }

    /**
     * Detach fragment with transition animation
     *
     * @param lastFrag    fragment
     * @param frag        fragment
     * @param transitMode mode
     */
    public void detachFragment(Fragment lastFrag, Fragment frag, int transitMode) {
        FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
        fragmentTransaction.setTransition(transitMode);
        fragmentTransaction.detach(frag);
        fragmentTransaction.commit();
        fragmentManager.executePendingTransactions();
    }

    /**
     * Back to fragment (popBackStack())
     *
     * @param fragment
     */
    public void backFragment(Fragment fragment) {
        if (fragment != null && !fragment.isRemoving()) {
            this.getSupportFragmentManager().popBackStack();
        }
    }

    public List<Fragment> getFragments() {
        return fragmentManager.getFragments();
    }

    public Fragment getLastFragment() {
        List<Fragment> fragmentList = getFragments();
        Fragment returnFrag = null;
        if (fragmentList != null && fragmentList.size() > 0) {

            Iterator<Fragment> itFrag = fragmentList.listIterator();
            while (itFrag.hasNext()) {
                Fragment f = itFrag.next();
                if (null != f) {
                    returnFrag = f;
                }
            }
        }

        return returnFrag;
    }

    public Fragment getLastLastFragment() {
        List<Fragment> fragmentList = getFragments();

        int fragmentListSize = fragmentList.size();

        if (fragmentList != null && fragmentListSize > 1) {

            int offset = 0;

            Fragment lastFragment = fragmentList.get(fragmentListSize - 1);
            if (null == lastFragment) {
                offset = 1;
            }

            Fragment f = null;

            if (fragmentListSize > (1 + offset)) {
                f = fragmentList.get(fragmentListSize - (2 + offset));
            }

            if (f == null) {
                if (fragmentList.size() > (2 + offset)) {

                    return fragmentList.get(fragmentListSize - (3 + offset));
                } else {
                    return null;
                }
            } else {
                return f;
            }
        } else {
            return null;
        }
    }

    /**
     * Add custom animation
     *
     * @param fragmentTransaction fragment
     * @param animation           (POP/PUSH LEFT/PUSH RIGHT)
     */
    public void addCustomAnimation(FragmentTransaction fragmentTransaction, FragmentCustomAnimation animation) {
        if (animation == FragmentCustomAnimation.PUSH_LEFT) {
            fragmentTransaction.setCustomAnimations(R.anim.in_from_left, R.anim.out_to_right, R.anim.in_from_right,
                    R.anim.out_to_left);
        }

        if (animation == FragmentCustomAnimation.PUSH_RIGHT) {
            fragmentTransaction.setCustomAnimations(R.anim.in_from_right, R.anim.out_to_left, R.anim.in_from_left,
                    R.anim.out_to_right);
        }

        if (animation == FragmentCustomAnimation.POP) {
            fragmentTransaction.setCustomAnimations(R.anim.pop_in_bottom, R.anim.pop_in_top, R.anim.pop_out_bottom,
                    R.anim.pop_out_top);
        }
        if (animation == FragmentCustomAnimation.EXPLODE) {
            //fragmentTransaction.setTransitionTy
        }
    }

}