LoginSignup
16
17

More than 5 years have passed since last update.

FragmentのトランジションでXML以外のアニメーションを指定する

Posted at

Fragmentのトランジション(切り替えアニメーション)を指定する場合、FragmentTransaction#setCustomAnimations()またはFragmentTransaction#setTransition()を使用しますが、これらはリソースで定義されたアニメーションか、標準で定義されたアニメーションしか指定できません。
XMLで表現できないような高度なアニメーションを指定したい場合には以下の方法で行うことができます。

Support Library v4を使う場合

Fragment#onCreateAnimation(int, boolean, int)は切り替えアニメーションの生成時に呼ばれ、第一引数にはFragmentTransaction#setTransition(int)で指定したトランジション識別子が渡されます。
この事を利用し、独自のトランジション識別子を定義してそれに応じたAnimationを返すようにします。

CustomFragment.java
public class CustomFragment extends Fragment {

    // FragmentTransaction.TRANSIT_XXXと重複しないIDを定義
    public static final int TRANSIT_HOGE = 0x10000;

    @Override
    public Animation onCreateAnimation(int transit, boolean enter, int nextAnim) {
        if (transit == TRANSIT_HOGE) {
            Animation anim;
            if (enter) {
                // enter用アニメーションを生成
                anim = new HogeAnimation(...);
                ...
            } else {
                // exit用アニメーションを生成
                anim = new HugaAnimation(...);
                ...
            }
            return anim;
        } else {
            return super.onCreateAnimation(transit, enter, nextAnim);
        }
    }
}
FragmentTransactionの実行
getSupportFragmentManager()
  .beginTransaction()
  .replace(container, newFragment)
  .setTransition(CustomFragment.TRANSIT_HOGE)
  .commit();

既存のトランジションIDと重複しないIDを定義することで、既存の動作を変えずに新しいアニメーションを追加定義することができます。

Support Libraryを使わない場合

onCreateAnimation()onCreateAnimator()に変わり、返すオブジェクトがAnimationからAnimatorに変わります。それ以外は一緒だと思います。

16
17
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
16
17