안드로이드개발

Navigation Graph 로 BottomBar 설정하기

아뵹젼 2022. 1. 8.

navigation 을 이용해서 Bottom Navigation 의 fragment 들을 구성하는 방법이다.

먼저 menu 와 navigation 에 필요한 xml 들을 각각 생성해주었다.

 

 

- Navigation xml

메뉴 선택시 이동할 Fragment 네 개를 생성하였다.

 

 

- menu xml

메뉴의 item 4개를 생성하고 아이콘, title 으로 구성하였다.

이때 Navigation 과 Menu 에 서로 매칭되는 아이템의 id 는 같아야 한다.

 

 

- MainActivity 

그런 다음 MainActivity 에서 navigationController를 설정해주면 된다. 

 

<?xml version="1.0" encoding="utf-8"?>
<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=".ui.main.MainActivity">

    <!-- ID must to be 'nav_host_fragment_container' -->
    <androidx.fragment.app.FragmentContainerView
        android:id="@+id/nav_host_fragment_container"
        android:name="androidx.navigation.fragment.NavHostFragment"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        app:layout_constraintVertical_weight="1"
        app:defaultNavHost="true"
        app:navGraph="@navigation/navigation"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintBottom_toTopOf="@+id/main_bottom_navigation"/>

    <com.google.android.material.bottomnavigation.BottomNavigationView
        android:id="@+id/main_bottom_navigation"
        android:layout_width="match_parent"
        android:layout_height="56dp"
        app:itemRippleColor="@null"
        app:labelVisibilityMode="labeled"
        app:menu="@menu/navi_menu"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/nav_host_fragment_container"
        app:layout_constraintBottom_toBottomOf="parent"/>

</androidx.constraintlayout.widget.ConstraintLayout>

activity_main 에서는 Fragment 가 보여질 FragmentContainerViewBottomnavigation 을 설정해주면 된다.

 

+ 또한 버튼 클릭이나 이벤트 발생 시 Fragment 전환이 일어나게 하고 싶다면,

먼저 navigation xml 의 design 을 이용해 화면 간 연결을 해준다.

그러면 다음과 같은 action 이 코드상에 생성이 된다.

<fragment
    android:id="@+id/menu_partnerFragment"
    android:name="com.example.duos.ui.main.home.HomeFragment"
    android:label="homeFragment">

    <action
        android:id="@+id/action_menu_partnerFragment_to_menu_friendFragment3"
        app:destination="@id/menu_friendFragment" />
</fragment>

 

그런 다음

navController.navigate(R.id.action_menu_partnerFragment_to_menu_friendFragment3)

을 navController.navigate 를 사용한다면 화면 전환이 가능하게 된다.

댓글