프래그먼트에서 xml대신 컴포즈로 뷰 완전히 대체하기

MSU·2025년 1월 25일

Android

목록 보기
31/36

xml방식에서 컴포즈로 대체하는 과정에서
프래그먼트의 onCreateView 코드를 아래와 같이 작성했었다.

변경 전

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        // Inflate the layout for this fragment
        super.onCreateView(inflater, container, savedInstanceState)

        binding.composeViewJoinStep1EmailAndPw.apply {
            setViewCompositionStrategy(ViewCompositionStrategy.DisposeOnViewTreeLifecycleDestroyed)
            setContent {
                JoinStep1EmailAndPwScreen(joinStep1EmailAndPwViewModel)
            }
        }
        return binding.root
    }

애초에 바인딩 객체를 리턴할 필요 없이 컴포즈뷰만 리턴해도 된다고 한다.
나는 컴포즈뷰만 리턴해도 된다는 이야기가 binding.composeView로 xml에서 작성한 컴포즈뷰를 이야기하는 건 줄 알았는데 그게 아니라 ComposeView 클래스의 객체를 말하는 것이었다.(코드 상으로 view 객체를 직접 작성하는 것 처럼)

변경 후

아래와 같이 변경하면 뷰바인딩도 필요없어지니 베이스프래그먼트 클래스를 상속할 필요도 없어진다

override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        // Inflate the layout for this fragment
        super.onCreateView(inflater, container, savedInstanceState)

        return ComposeView(requireContext()).apply {
            setViewCompositionStrategy(ViewCompositionStrategy.DisposeOnViewTreeLifecycleDestroyed)
            setContent {
                JoinStep1EmailAndPwScreen(joinStep1EmailAndPwViewModel)
            }
        }
    }

전체 프래그먼트 코드

class JoinStep1EmailAndPwFragment : Fragment() {

    private val joinStep1EmailAndPwViewModel: JoinStep1EmailAndPwViewModel by activityViewModels()

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        // Inflate the layout for this fragment
        super.onCreateView(inflater, container, savedInstanceState)

        return ComposeView(requireContext()).apply {
            setViewCompositionStrategy(ViewCompositionStrategy.DisposeOnViewTreeLifecycleDestroyed)
            setContent {
                JoinStep1EmailAndPwScreen(joinStep1EmailAndPwViewModel)
            }
        }
    }

}

기존 프래그먼트에서 뷰바인딩을 하고 있는 베이스 프래그먼트 상속도 지울 수 있었다.
추후에 컴포즈 변환 작업이 완료되면 프래그먼트도 사라지고 메인액티비티에서 컴포저블 함수를 호출하는 방식으로 바뀔 것이다.

profile
안드로이드공부

0개의 댓글