[Jetpack Compose] 1. Compose 기본 사항(4) #View에서 Compose로 Migration #ViewCompositionStrategy

0

Jetpack Compose

목록 보기
4/11
post-thumbnail
post-custom-banner

[Jetpack Compose] 1. Compose 기본 사항(4) #View에서 Compose로 Migration #ViewCompositionStrategy

📌참고자료

Accelerate with tooling

  • Android Studio Files>Settings>Editor>Live Edit 설정
  • Composable 디버깅: layout inspector 사용

Migrate from the View system

  • Compose is designed with View interoperability

  • Once all the contents are in compose
    -> remove fragments entirely & replace with screen level composable
    -> use navigation compose to navigate & pass data between composables

📌참고자료

  • add build feature & dependencies in build.gradle(app)
buildFeatures{
	compose true
}
  • 레이아웃 xml 파일에 composable로 변경할 뷰가 들어갈 위치 ComposeView 태그 사용하여 저으이
    • 태그 내에 레이아웃 위치만(ex. layout constraints) 정의
    • 레이아웃의 다른 요소들(ex. margin, padidng)은 composable에서 정의
      -> single source of truth 보장
<androidx.compose.ui.platform.ComposeView
        android:id="@+id/compose_view"
        android:layout_width="match_parent"
        android:layout_height="match_parent"/>
  • onCreateView 함수 내부에서 View에 setContent 함수 호출
override fun onCreateView(...): View? {
        val binding = DataBindingUtil.inflate<FragmentPlantDetailBinding>(
            inflater, R.layout.fragment_plant_detail, container, false
        )
		
        binding.composeView.setContent {
            MaterialTheme {
                PlantDetailDescription()
            }
        }
        //...
}
  • Fragment에서 ViewModel을 사용하여 UI 상태(데이터)를 관리하는 경우, composable의 파라미터로 ViewModel 객체 전달
    • memory leak 걱정할 필요 X -> ViewModel의 생명주기가 fragment나 composable보다 길다
  • composable 안에서 Viewmodel의 LiveData를 사용하기 위해 observeAsState 함수 사용
    @Composable
    <T : Any?> LiveData<T>.observeAsState()
  • observeAsState
    • LiveData의 Extension function
    • LiveData의 value를 observing하여 State로 represent하는 함수
    • LiveData의 value 변경 -> state 업데이트 -> state usage가 있는 모든 composable의 recomposition 트리거
    • inner observer는 composable이 dispose되거나 LiveData의 LifecycleOwner이 Lifecycle.State.DESTROYED 상태가 되면 자동으로 제거됨
  • composable 내에서 Context 객체에 접근하기 위해서 LocalContext.current 사용
    -> context 값 파라미터로 전달하지 않아도 됨
  • Compose는 아직 HTML 코드 랜더링 지원 X -> Compose 안에 View 표시해야 -> Android View 사용
    • HTML markup을 표시하는 Composable function X
    • Text composable 파라미터로 Spanned 타입 받을 수 X
@Composable
@UiComposable
fun <T : View> AndroidView(
    factory: (Context) -> T,
    modifier: Modifier = Modifier,
    update: (T) -> Unit = NoOpUpdate
): Unit
  • Android View API
    • a composable to create a View Programmatically
    • factory lambda: used to construct a View
    • update lambda: gets invoked when the View has been inflated & on recompositions
  • Compose disposes of the Composition whenever the ComposeView becomes detached from a window
    -> Fragment 내에서 ComposeView를 사용하는 경우, Compose의 생명주기 Fragment View의 생명주기와 맞춰야
    -> setViewCompositionStrategy 함수로 ViewCompositionStrategy 설정
  • ViewCompositionStrategy
    • Compose UI View(ex. ComposeView)의 Composition 관리 strategy
    • DisposeOnDetachedFromWindow
    • DisposeOnDetachedFromWindowOrReleasedFromPool
      • disposes the composition whenever the view becomes detached from a window
        unless it is part of a pooling container(ex. RecyclerView)
      • current default strategy
    • DisposeOnLifecycleDestroyed
    • DisposeOnViewTreeLifecycleSDestroyed
      • disposes the composition when the LifecycleOwner returned by findViewTreeLifecycleOwner of the*next window the view is attached to is destroyed
      • appropriate for Compose UI views that share a 1-1 relationship with their closest LifecycleOwner, such as a Fragment view.
profile
Be able to be vulnerable, in search of truth
post-custom-banner

0개의 댓글