본문 바로가기
android

[fragment lifecycle] onCreatView와 onViewCreated

by arirang_ 2023. 1. 5.

 

프로젝트에서 tts(Text to Speech) 부분을 하다가 오류가 떠서 정리해본다.

Activity에서 fragment가 나올 때 fragment의 tts가 실행되어야 하는데, fragment가 나올 때 fragment의 tts가 작동되지 않았다.  아무 음성도 나지 않다가 fragment의 텍스트를 터치하면 Activity의 tts가 실행되었다..

 

문제는 fragment 부분있었다.

override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {
        viewBinding = FragmentTutorialTxt2Binding.inflate(layoutInflater)
        return viewBinding.root

        tts = TextToSpeech(context, this)
    }

여기서 tts의 위치가 문제였다. tts를 onCreateView에 넣는 것이 아니라, onViewCreated에 넣어야 했다. 

override fun onCreateView(
    inflater: LayoutInflater,
    container: ViewGroup?,
    savedInstanceState: Bundle?
): View {
    viewBinding = FragmentTutorialTxt2Binding.inflate(layoutInflater)
    return viewBinding.root
    
}

override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
    super.onViewCreated(view, savedInstanceState)
    tts = TextToSpeech(context, this)         //activity, context 둘 다 됨
}

이런식으로 말이다. 위의 코드처럼 작성했더니
activity에서 fragment가 나올 때, activity의 tts가 아닌 fragment의 tts가 잘 진행되었다. 


fragment에서 onCreatView와 onViewCreated의 차이는 무엇일까?

이것은 fragment의 lifecycle이다.

fragment lifecycle

● onCreate()

- Fragment 자체가 생성된다.

- Fragment View가 아직 생성되지 않은 상태이다. 

- View와 관련된 작업X

 

● onCreateView()

-  Fragment View를 직접 생성하고 inflate 한다.
( Fragment View가 초기화되고, 정상적으로 초기화가 되었다면 View 객체를 반환한다.)

 

● onViewCreated()

- onCreateView()를 통해 반환된 View 객체가 onViewCreated()의 파라미터로 전달된다.

- onViewCreated() 에서부터 Fragement View의 lifecyele이 INITIALIZED 상태로 업데이트 된다.

(Fragment View가 완전히 생성되었음을 보장한다)

- 따라서,

1) View의 초기값을 설정

2) LiveData observing

3) RecyclerView나 ViewPager2에 사용될 Adatper 세팅등을 해줄 수 있다.

 

 

 

 

 

※ 참고 (정리하는데 도움된 블로그 주소입니다!)

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

https://readystory.tistory.com/199

https://velog.io/@jeongminji4490/Android-Fragment-Lifecycle