본문 바로가기
Android

[Android/Kotlin] nav, appBarConfiguration 을 사용한 Fragment

by noddu 2022. 2. 27.
728x90
반응형

●mobile_navigation.xml

<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/mobile_navigation"
    app:startDestination="@+id/nav_main">

    <fragment
        android:id="@+id/nav_main"
        android:name="com.example.companymarket.ui.main.MainframeFragment"
        android:label="@string/menu_main"
        tools:layout="@layout/fragment_mainframe"/>
	....
</navigation>

 

이런식으로 navigation안에 <fragment>들을 넣어준다

id값을 적고, name값을 디렉토리 위치에 맞게 적어준다

layout =  표시될 xml 파일을 적는다

 

 

 


●MainActivity

 

private lateinit var appBarConfiguration: AppBarConfiguration

AppBarConfiguration은 onSupportNavigateUp()을 재정의할 때도 사용하므로 onCreate() 외부에 선언한다

 

 

val navController = findNavController(R.id.nav_host_fragment_content_main)

onCreate() 내부에 아래에있는 xml파일을 선언한다


 

●nav_host_fragmet_content_main.xml

<fragment
    android:id="@+id/nav_host_fragment_content_main"
    android:name="androidx.navigation.fragment.NavHostFragment"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    app:defaultNavHost="true"
    app:layout_constraintLeft_toLeftOf="parent"
    app:layout_constraintRight_toRightOf="parent"
    app:layout_constraintTop_toTopOf="parent"
    app:navGraph="@navigation/mobile_navigation"/>

여기에 fragment가 들어간다


●activity_main_drawer.xml

<menu xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    tools:showIn="navigation_view">

    <group android:checkableBehavior="single">
        <item
            android:id="@+id/nav_main"
            android:title="@string/menu_main"/>
            ...
</menu>

drawer에서 선택할 fragment의 id를 각각 넣어주기

( 보여지는 이름은 title로 표시 )

 


●MainActivity

appBarConfiguration = AppBarConfiguration(setOf(R.id.nav_main,
    R.id.nav_home, R.id.nav_gallery, R.id.nav_slideshow), drawerLayout)
setupActionBarWithNavController(navController, appBarConfiguration)
navView.setupWithNavController(navController)

 

onCreate() 메서드에서 appBarConfiguration = item의 id값들을 setOf해주고

setupActionBarWithNavController()를 호출한다

실행 후 menu(위의 drawer)에서 id값을 누르면 그 id값을 가진 fragment가 표시된다

 

 

반응형