본문 바로가기
Development/Android

[Android] Fragment Lifecycle - onCreateAnimation 은 무엇일까?

by du.it.ddu 2023. 1. 14.
반응형

안드로이드 앱을 개발하다보면 Fragment를 자주 사용하게 된다.
특히, Jetpack Navigation Component를 사용한다면 Fragment 기반의 Single Activity Application으로 개발하게 될 것이다.
그러다보니 Fragment의 Lifecycle에 대한 이해가 중요해지게 되었다.

https://developer.android.com/guide/fragments/lifecycle

Fragment는 Activity와 달리, Fragment가 Attach, Detach되는 함수와
뷰가 생성되고 파괴되는 함수가 Lifecycle에 존재한다.

그런데 여기서 잘 알려지지 않은 라이프 사이클 함수도 있다.
바로 onCreateAnimation이다.

package androidx.fragment.app;

public class Fragment {
    ...
    
    /**
     * Called when a fragment loads an animation. Note that if
     * {@link FragmentTransaction#setCustomAnimations(int, int)} was called with
     * {@link Animator} resources instead of {@link Animation} resources, {@code nextAnim}
     * will be an animator resource.
     *
     * @param transit The value set in {@link FragmentTransaction#setTransition(int)} or 0 if not
     *                set.
     * @param enter {@code true} when the fragment is added/attached/shown or {@code false} when
     *              the fragment is removed/detached/hidden.
     * @param nextAnim The resource set in
     *                 {@link FragmentTransaction#setCustomAnimations(int, int)},
     *                 {@link FragmentTransaction#setCustomAnimations(int, int, int, int)}, or
     *                 0 if neither was called. The value will depend on the current operation.
     */
    @MainThread
    @Nullable
    public Animation onCreateAnimation(int transit, boolean enter, int nextAnim) {
        return null;
    }
 }

Fragment의 코드를 직접 확인해보면, 주석으로 설명해주고 있다.
onCreateAnimation 함수는 FragmentTransacion의 setCustomAnimation함수가 호출되면 호출된다.
즉, Fragment를 Commit할 때 Custom Animation을 적용할 때 호출된다는 것이다.
만약 Navigation Component를 사용한다면 NavOptions에 Animation 옵션을 적용하면 호출된다.

또한 Fragment의 애니메이션에 대한 정보도 파라미터로 확인할 수 있다.

그렇다면 이것은 어떻게 활용할 수 있을까?

onCreateAnimation은 onResume 다음에 호출된다.
즉, 화면이 다 그려지고 비로소 상호작용이 될 수 있는 상태 이후에 불린다.
따라서 Fragment가 나타나고 화면이 다 그려진 후, 애니메이션이 끝나는 시점을 알아야할 때 쓸 수 있다.

나 같은 경우는, Fragment에서 다음 Fragment로 이동하는 이벤트 발생 시에,
애니메이션 도중에 호출되면 부자연스럽게 깜빡이는 현상이 있었다.
이 현상을 제거하기 위해 onCreateAnimation을 Override하고,
애니메이션 완료 콜백을 받은 후 이벤트를 수신할 수 있도록 변경하여 개선할 수 있었다.

Fragment는 앱 개발 시 아주 많이 활용되는 만큼,
내부에서 제공하는 함수들에 대한 높은 이해도도 중요한 것 같다.

반응형