본문 바로가기
안드로이드

안드로이드 - Fragment

by minsol Kim 2022. 5. 1.

Fragment

- 재사용가능한 사용자 UI모듈

- 프래그먼트에서 레이아웃이나 입력 처리 등이 모두 가능함

- 독립적으로 존재할 수 없고, 액티비티나 다른 프래그먼트 내에 만들어져야 함

 

Fragment를 액태비티에 넣기

 

액티비티 레이아웃 xml에 정적으로 넣기

<androidx.fragment.app.FragmentContainerView

/>

<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <androidx.fragment.app.FragmentContainerView
        android:id="@+id/nav_host_fragment"
        android:name="androidx.navigation.fragment.NavHostFragment"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:defaultNavHost="true"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:navGraph="@navigation/nav" />

</androidx.constraintlayout.widget.ConstraintLayout>

Fragment와 ViewModel

액티비티와 프래그먼트 간에, 또는 프래그먼트들끼리 데이터를 공유할 수 있는 방법으로 ViewModel을 사용할 수 있음.

액티비티, 프래그먼트에서 ViewModel 객체에

데이터를 쓰는 곳에서는 ViewModel 객체에 포함된 LiveData객체에 값을 쓰고

데이터를 받는 곳에서는 ViewModel 객체에 포함된 LiveData 객체를 observe

 

댓글