본문 바로가기
안드로이드 코틀린

[Kotlin][Android] setOnItemSelectedListener 을 이용한 Bottom Navigation

by teamnova 2022. 5. 7.
728x90

스틱코드에서 바텀네비게이션을 다뤘었는데요

 

그럼에도 불구하고 다시 다루는 이유는 기존에 BottomNavigationView, setOnNavigationItemSelectedListener를 사용해서 바텀네비게이션을 구혔했었습니다.

 

하지만, 현재 deprecate 되었습니다.

참조 링크 : https://github.com/material-components/material-components-android/blob/master/lib/java/com/google/android/material/bottomnavigation/BottomNavigationView.java#L223

 

GitHub - material-components/material-components-android: Modular and customizable Material Design UI components for Android

Modular and customizable Material Design UI components for Android - GitHub - material-components/material-components-android: Modular and customizable Material Design UI components for Android

github.com

 

하지만 다른 구현 방법이 있는데요 공식문서에서도 setOnItemSelectedListener 를 사용하라고 지침을 해놨습니다.

 

오늘은 setOnNavigationItemSelectedListener 가 아닌 setOnItemSelectedListener 로 바텀 네비게이션 을 구현할겁니다.

 

1. 의존성 라이브러리 추가

    implementation 'com.google.android.material:material:1.4.0'

 

2. MainActivity 의 레이아웃에 프래그먼트를 표출할 FrameLayout 과 bottomNavigationView 추가 

(* 위치적인 부분에 대한 속성을 제거 했으니 새로 정의 해주시면 됩니다.)

        <FrameLayout
            android:id="@+id/fragment_container"
            android:layout_width="match_parent"
            tools:context=".view.ui.main.MainActivity" />

        <com.google.android.material.bottomnavigation.BottomNavigationView
            android:id="@+id/bottom_navigation"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            app:menu="@menu/menu" />

이렇게 하고나면 "@menu/menu" 부분이 빨간색일텐데 이부분은 3 번을 통해서 해결이 됩니다.

 

3. menu.xml 추가 

res>new>Android Resource File >Resource type 은 Menu 를 통해서 파일을 만들면되고

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
    <item
        android:id="@+id/nav_one"
        android:icon="@drawable/home_variant"
        android:title="fragment_one"/>
    <item
        android:id="@+id/nav_two"
        android:icon="@drawable/web"
        android:title="fragment_two"/>
    <item
        android:id="@+id/nav_three"
        android:icon="@drawable/text_box_multiple"
        android:title="fragment_three"/>
</menu>

4. OneFragment, TwoFragment, ThreeFragment 추가

 

5. 프래그먼트를 담을 Activity에서 화면전환에 대한 정의하기

 

아래 코드블럭을 onCreate() 부분에 넣어줍니다.

 

아래코드에서 BottomNavigationView 에 대한 정의는 없으니 주의하세요

        
        changeFragment(oneFragment())
        
        BottomNavigationView.bottomNavigation.run {
       
            setOnItemSelectedListener { item ->
            
                when (item.itemId) {

                    R.id.nav_one -> {
                        changeFragment(OneFragment())
                    }
                    R.id.nav_two -> {
                        changeFragment(TwoFragment())
                    }
                    R.id.nav_three -> {
                        changeFragment(ThreeFragment())
                    }

                }
                true
            }
        }

 

changeFragment 함수

    // 프래그먼트 화면 전환
    private fun changeFragment(fragment: Fragment) {
        getSupportFragmentManager()
            .beginTransaction()
            .replace(R.id.fragment_container, fragment)
            .commit()
    }

 

이러면 완성입니다.