xml과 Jetpack Compose 같이 쓰기

James_·2022년 7월 15일
2

Jetpack Compose

실무에는 아직 xml을 많이 쓰지만 Jetpack Compose에 대한 관심이 자연스럽게 생기게 되었다.
이번 사이드 프로젝트에 써보면서 연습을 하기로 했다.

project build.gradle

buildscript {
    ext{
     compose_version = '1.1.1'
    }
    repositories {
        google()
        mavenCentral()
    }
    ...
    }

compose version을 추가해준다.

app build.gradle

   
   
       buildFeatures{
        ...
        compose true
    }

    composeOptions{
        kotlinCompilerExtensionVersion compose_version
        kotlinCompilerVersion '1.6.10'
    }

   
   dependencies{
   ...
   // jetpack compose
    implementation "androidx.compose.ui:ui:$compose_version"
    implementation "androidx.compose.material:material:$compose_version"
    implementation "androidx.compose.ui:ui-tooling-preview:$compose_version"
    androidTestImplementation "androidx.compose.ui:ui-test-junit4:$compose_version"
    }

여기서 주의할 점은 코틀린 버전을 적절한 버전으로 설정해줘야한다.

Fragment 생성

fragment_xml

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
	>

    <androidx.compose.ui.platform.ComposeView
        android:id="@+id/compose_view"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        />

</androidx.constraintlayout.widget.ConstraintLayout>

xml에 compose view를 추가해준다.

fragment.kt

class Fragment : Fragment() {
    private var _binding:ViewBinding?=null
    private val binding get() = _binding!!
    
    private val viewModel: ViewModel by viewModels()

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {
        _binding = FragmentEditRecordBinding.inflate(inflater, container, false)
        binding.editRecordComposeView.apply {
            setViewCompositionStrategy(ViewCompositionStrategy.DisposeOnViewTreeLifecycleDestroyed)
            setContent {

            }
        }
        return binding.root
    }
        override fun onDestroyView(){
        super.onDestroyView()
        _binding = null
    }
}

onCreateView에서 설정해주고 setContent에 Composable을 추가해주면 끝

profile
Android 개발자

0개의 댓글