개발일지

Android in A..Z - Navigation (기본) 본문

Android (안드로이드)/Navigation

Android in A..Z - Navigation (기본)

강태종 2021. 4. 6. 05:19

Navigation

Navigation은 UI의 전환을 쉽게 도와주고 시각화 하는 Jetpack Architecture입니다. 기존의 Activity 중심의 UI 구성이 아닌 Fragment와 FragmentTransaction을 통해 UI를 구성하여 더 성능이 좋습니다.


구성

  • NavGraph : 탐색에 관련된 정보가 모여있는 XML 리소스입니다. UI 대상과, UI 탐색에 관한 정보가 저장됩니다.
  • NavHost : 탐색 그래프에서 UI 대상을 표시하는 빈 컨테이너입니다. NavHostFragment로 표현합니다.
  • NavController : NavHost에서 탐색을 관리하는 객체입니다.

장점

  • 프래그먼트 트랜잭션 처리
  • 기본적으로 '위로'와 '뒤로'작업을 올바르게 처리 (위로 버튼은 앱을 종료하지 않는다.)
  • 애니메이션과 전환에 표준화된 리소스 제공
  • 딥링크 구현 및 처리
  • 최소한의 작업으로 UI패턴 포함
  • Safe Arg : UI를 전환할 때 데이터를 안정성있게 제공
  • ViewModel 지원

Dependency

dependencies {
  def nav_version = "2.3.3"

  // Java language implementation
  implementation "androidx.navigation:navigation-fragment:$nav_version"
  implementation "androidx.navigation:navigation-ui:$nav_version"

  // Kotlin
  implementation "androidx.navigation:navigation-fragment-ktx:$nav_version"
  implementation "androidx.navigation:navigation-ui-ktx:$nav_version"
}

NavGraph(탐색 그래프) 만들기

res/navigation 폴더 안에 navigation파일을 생성한다.

 

 

<?xml version="1.0" encoding="utf-8"?>
<navigation 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:id="@+id/activity_main_navigation"
    app:startDestination="@id/AFragment">

    <fragment
        android:id="@+id/AFragment"
        android:name="com.taetae98.navigation.fragment.AFragment"
        android:label="A"
        tools:layout="@layout/fragment_a" >
        <action
            android:id="@+id/action_AFragment_to_BFragment"
            app:destination="@id/BFragment"
            app:enterAnim="@anim/from_right_to_center"
            app:exitAnim="@anim/from_center_to_left"
            app:popEnterAnim="@anim/from_left_to_center"
            app:popExitAnim="@anim/from_center_to_right" />
    </fragment>
    <fragment
        android:id="@+id/BFragment"
        android:name="com.taetae98.navigation.fragment.BFragment"
        android:label="B"
        tools:layout="@layout/fragment_b" >
        <action
            android:id="@+id/action_BFragment_to_CFragment"
            app:destination="@id/CFragment"
            app:enterAnim="@anim/from_right_to_center"
            app:exitAnim="@anim/from_center_to_left"
            app:popEnterAnim="@anim/from_left_to_center"
            app:popExitAnim="@anim/from_center_to_right" />
    </fragment>

    <fragment
        android:id="@+id/CFragment"
        android:name="com.taetae98.navigation.fragment.CFragment"
        android:label="C"
        tools:layout="@layout/fragment_c" >
        <action
            android:id="@+id/action_CFragment_to_DFragment"
            app:destination="@id/DFragment"
            app:popUpTo="@id/AFragment"
            app:enterAnim="@anim/from_right_to_center"
            app:exitAnim="@anim/from_center_to_left"
            app:popEnterAnim="@anim/from_left_to_center"
            app:popExitAnim="@anim/from_center_to_right" />
    </fragment>
    <fragment
        android:id="@+id/DFragment"
        android:name="com.taetae98.navigation.fragment.DFragment"
        android:label="D"
        tools:layout="@layout/fragment_d"
        app:enterAnim="@anim/from_right_to_center"
        app:exitAnim="@anim/from_center_to_left"
        app:popEnterAnim="@anim/from_left_to_center"
        app:popExitAnim="@anim/from_center_to_right" />
    <fragment
        android:id="@+id/inputFragment"
        android:name="com.taetae98.navigation.fragment.InputFragment"
        android:label="Input"
        tools:layout="@layout/fragment_input">
        <action
            android:id="@+id/action_inputFragment_to_outputFragment"
            app:destination="@id/outputFragment" />
    </fragment>
    <fragment
        android:id="@+id/outputFragment"
        android:name="com.taetae98.navigation.fragment.OutputFragment"
        android:label="@string/safe_args"
        tools:layout="@layout/fragment_out">
        <argument
            android:name="args"
            app:argType="string"
            app:nullable="true"
            android:defaultValue="@null" />
    </fragment>
    <fragment
        android:id="@+id/deepLinkFragment"
        android:name="com.taetae98.navigation.fragment.DeepLinkFragment"
        android:label="DeepLink"
        tools:layout="@layout/fragment_deep_link">
        <argument
            android:name="arg"
            app:argType="string"
            app:nullable="true" />
        <deepLink
            android:id="@+id/deeplink"
            app:uri="navigation://taetae98.com?arg={arg}" />
    </fragment>
    <fragment
        android:id="@+id/pendingFragment"
        android:name="com.taetae98.navigation.fragment.PendingFragment"
        android:label="Pending"
        tools:layout="@layout/fragment_pending_intent"/>
    <fragment
        android:id="@+id/UIFragment"
        android:name="com.taetae98.navigation.fragment.UIFragment"
        android:label="UIFragment" />

</navigation>
  • UI 대상 : Fragment, Dialog 등 UI Controller가 될 수 있다.
  • app:startDestination : NavGraph의 시작점이다.
  • android:name : UI 대상의 Class명이다.
  • android:label : UI 대상이 표현될 때 Toolbar에 표시되는 Text이다.

NavHost 만들기

Activity에 NavHost를 추가한다.

<?xml version="1.0" encoding="utf-8"?>
<layout 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">

    <data>

    </data>

    <androidx.drawerlayout.widget.DrawerLayout
        android:id="@+id/drawerLayout"
        android:layout_width="match_parent"
        android:layout_height="match_parent">
        <androidx.constraintlayout.widget.ConstraintLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent">
            <com.google.android.material.appbar.MaterialToolbar
                android:id="@+id/toolbar"
                android:layout_width="match_parent"
                android:layout_height="?attr/actionBarSize"
                app:layout_constraintTop_toTopOf="parent"
                app:layout_constraintStart_toStartOf="parent"
                app:layout_constraintEnd_toEndOf="parent"/>

            <androidx.fragment.app.FragmentContainerView
                android:id="@+id/nav_host_fragment"
                android:name="androidx.navigation.fragment.NavHostFragment"
                android:layout_width="0dp"
                android:layout_height="0dp"
                app:defaultNavHost="true"
                app:navGraph="@navigation/activity_main_navigation"
                app:layout_constraintTop_toBottomOf="@id/toolbar"
                app:layout_constraintStart_toStartOf="parent"
                app:layout_constraintEnd_toEndOf="parent"
                app:layout_constraintBottom_toBottomOf="parent"/>
        </androidx.constraintlayout.widget.ConstraintLayout>


        <com.google.android.material.navigation.NavigationView
            android:id="@+id/navigation"
            android:layout_gravity="start"
            android:layout_width="wrap_content"
            android:layout_height="match_parent"

            app:menu="@menu/activity_main_navigation_menu" />

    </androidx.drawerlayout.widget.DrawerLayout>
</layout>

Navigation은 Activity를 UI Controller가 아닌 Android의 EntryPoint로 지향한다. UI Controll을 NavHost에게 넘기며 FragmentContainerView를 NavHost로 임명하고 UI 활동을 담당한다.

  • android:name : NavHostFragment를 지정하며 NavHost로 임명한다.
  • defaultNavHost : true를 지정하면 백버튼에 대한 컨트롤을 가져간다.
  • navGraph : NavGraph를 지정한다.

예제소스

class MainActivity : BaseActivity(), DataBinding<ActivityMainBinding> {
    override val binding: ActivityMainBinding by lazy { DataBinding.get(this, R.layout.activity_main)}

    private val navController by lazy {
        (supportFragmentManager.findFragmentById(R.id.nav_host_fragment) as NavHostFragment).navController
    }

    private val appBarConfiguration by lazy {
        AppBarConfiguration(
            setOf(
                R.id.AFragment, R.id.inputFragment
            ),
            binding.drawerLayout
        )
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        onCreateSupportActionButton()
        onCreateNavigationView()
    }

    private fun onCreateSupportActionButton() {
        setSupportActionBar(binding.toolbar)
    }

    private fun onCreateNavigationView() {
        binding.navigation.setupWithNavController(navController)
    }

    override fun onBackPressed() {
        super.onBackPressed()
        with(binding) {
            if (drawerLayout.isDrawerOpen(navigation)) {
                drawerLayout.closeDrawer(navigation)
            } else {
                navController.navigateUp()
            }
        }
    }

    override fun onSupportNavigateUp(): Boolean {
        return navController.navigateUp(appBarConfiguration) || super.onSupportNavigateUp()
    }

    override fun setSupportActionBar(toolbar: Toolbar?) {
        super.setSupportActionBar(toolbar)
        setupActionBarWithNavController(navController, appBarConfiguration)
    }
}

Git (예제소스)

github.com/KangTaeJong98/Example/tree/main/Android/Navigation

 

KangTaeJong98/Example

My Example Code. Contribute to KangTaeJong98/Example development by creating an account on GitHub.

github.com

 

Comments