본문 바로가기
Android/Android Studio

[안드로이드/Kotlin] BottomNavigationView 사용, Fragment 전환

by YOONAYEON 2022. 5. 12.
BottomNavigationView

 

- 어플 하단의 아이콘을 눌렀을 때, 프래그먼트 전환을 해주는 위젯 

 

 

 

 

1. menu폴더 생성 후 bottom_nav_menu.xml파일 생성

 

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    xmlns:app="http://schemas.android.com/apk/res-auto">
    <item
        android:id="@+id/homeFragment"
        android:icon="@drawable/ic_bottom_home_no_select"	<!-- 아이콘 설정 -->
        app:showAsAction="always"		<!-- 항상 보이게끔 -->
        android:enabled="true"			<!-- 지정된 그룹에 있는 모든 메뉴들을 활성화 -->
        android:title="홈"				<!-- 아이콘과 함께 글씨 추가 -->
        tools:ignore="AlwaysShowAction" />
    <item
        android:id="@+id/lookFragment"
        android:icon="@drawable/ic_bottom_look_no_select"
        app:showAsAction="always"
        android:title="둘러보기" />
    <item
        android:id="@+id/searchFragment"
        android:icon="@drawable/ic_bottom_search_no_select"
        app:showAsAction="always"
        android:title="검색" />
    <item
        android:id="@+id/lockerFragment"
        android:icon="@drawable/ic_bottom_locker_no_select"
        app:showAsAction="always"
        android:title="보관함" />

</menu>

 

 

2. 각 메뉴 탭에 해당하는 Fragment의 xml파일 만들어주기

 

 

3. acitivity_main.xml파일 생성

 

- FrameLayout: 여러 개의 뷰들을 겹쳐서 배치

 

<?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=".MainActivity">

    <FrameLayout
        android:id="@+id/main_frm"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintBottom_toTopOf="@id/main_bnv"/>
        
    <com.google.android.material.bottomnavigation.BottomNavigationView
        android:id="@+id/main_bnv"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        app:itemIconSize="20dp"
        android:background="@color/white"
        app:itemIconTint="@drawable/btm_color_selector"
        app:itemTextColor="@drawable/btm_color_selector"
        app:labelVisibilityMode="labeled"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:menu="@menu/bottom_nav_menu" />

</androidx.constraintlayout.widget.ConstraintLayout>

 

 

 

4. MainActivity.kt 작성

 

class MainActivity : AppCompatActivity() {

    lateinit var binding: ActivityMainBinding

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = ActivityMainBinding.inflate(layoutInflater)
        setContentView(binding.root)

        initBottomNavigation()
    }
    
    private fun initBottomNavigation(){
        supportFragmentManager.beginTransaction()
            .replace(R.id.main_frm, HomeFragment())
            .commitAllowingStateLoss()

        binding.mainBnv.setOnItemSelectedListener { item ->
            when(item.itemId){
                R.id.homeFragment->{
                    supportFragmentManager.beginTransaction()
                        .replace(R.id.main_frm, HomeFragment())
                        .commitAllowingStateLoss()
                    return@setOnItemSelectedListener true
                }

                R.id.lookFragment->{
                    supportFragmentManager.beginTransaction()
                        .replace(R.id.main_frm, LookFragment())
                        .commitAllowingStateLoss()
                    return@setOnItemSelectedListener true
                }

                R.id.searchFragment->{
                    supportFragmentManager.beginTransaction()
                        .replace(R.id.main_frm, SearchFragment())
                        .commitAllowingStateLoss()
                    return@setOnItemSelectedListener true
                }

                R.id.lockerFragment->{
                    supportFragmentManager.beginTransaction()
                        .replace(R.id.main_frm, LockerFragment())
                        .commitAllowingStateLoss()
                    return@setOnItemSelectedListener true
                }
            }
            false
        }
    }
}

 

 

5. 프래그먼트 전환

 

class HomeFragment : Fragment() {

    lateinit var binding : FragmentHomeBinding

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        binding = FragmentHomeBinding.inflate(inflater, container, false)
        
        //이미지 클릭 시 다른 프래그먼트로 변경 
        binding.img.setOnClickListener{
        	(context as MainActivity).supportFragmentManager.beginTransaction()
            				.replace(R.id.main_frm, LookFragment())
                                    	.commitAllowingStateLoss()
        }
        
        return binding.root
    }
}

 

(context as MainActivity) : 프래그먼트를 어디서 변경하는지

replace(어느 것을 바꿀 것인지,  어떤것으로 바꿔주는지)

commitAllowIngStateLoss( ) : FragmentTransaction의 상태 변경