차지

[Android Study Jam] Unit 4: Navigation, Fragment 본문

Android/Android

[Android Study Jam] Unit 4: Navigation, Fragment

Cha_Ji 2021. 4. 9. 21:05

유닛 4에서는 Fragment화면을 오가는 navigation에 대해서 공부합니다.

Fragment

Fragment는 앱 UI의 재사용 가능한 부분을 나타냅니다.

자체 레이아웃을 정의 및 관리하고 자체 lifecycle을 보유하며 자체 입력 이벤트를 처리할 수 있습니다.

프래그먼트는 독립적으로 존재할 수 없습니다.

우선 프래그먼트를 추가해 activity_main.xml의 레이아웃에 넣습니다.

만든 TitleFragment 클래스에 onCreate() 메소드를 onCreateView()메소드로 변경합니다.

class TitleFragment : Fragment() {

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
        
    }
}

layout file에 fragment를 추가시킵니다.

<layout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto">

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:orientation="vertical">
            <fragment
                android:id="@+id/titleFragment"
                android:name="com.example.android.navigation.TitleFragment"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                />
        </LinearLayout>

</layout>

Navigation

fragment를 추가했으니 액티비티 내에서 특정 행동을 취하면 특정 fragment로 이동할 수 있게 해줘야합니다.

의존성을 추가하고, 그래프를 추가하는 과정으로 손쉽게 fragment를 사용할 수 있습니다.

먼저 build.gradle에서 의존성을 추가합니다.

ext {
        ...
        navigationVersion = "2.3.0"
        ...
    }
dependencies {
  ...
  implementation "androidx.navigation:navigation-fragment-ktx:$navigationVersion"
  implementation "androidx.navigation:navigation-ui-ktx:$navigationVersion"
  ...
}

 

그리고 navigation graph를 프로젝트에 추가합니다.

화면 전환을 디자인 에디터에서 정리할 수 있습니다.

 

  • 참고

developer.android.com/courses/study-jams

 

Android Study Jams  |  Android 개발자  |  Android Developers

Become an Android Developer. Learn how to build Android apps in Kotlin by following an online curriculum together with a study group.

developer.android.com

developer.android.com/guide/fragments