ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • 안드로이드 코틀린 : 프래그먼트 ( Fragment ) & Bottom Navigation View
    프로그래밍/Android(Kotlin) 2020. 6. 29. 21:46
    반응형

     

    안녕하세요, 랴파파입니다.

    오늘은 프래그먼트를 사용하여 아래와 그림과 같이 앱 화면 아래에 위치한 버튼을 클릭하면

    해당 프래그먼트(페이지)로 넘어가는 예제 프로그램을 만들어볼 예정입니다.

    여기서 프래그먼트는 아래 예제 프로그램에서 색칠되어 있는 부분이라고 볼 수 있습니다.

    해당 예제는 클릭뿐만 아니라 위의 프래그먼트(페이지)를 슬라이드로도 넘길 수 있습니다.

    그럼 시작하도록 하겠습니다!

     

    Fragment를 적용한 예제 프로그램 화면

     

    1. 레이아웃 ( Layout ) 구성

    먼저 위의 예제 프로그램의 화면에서 해당 페이지로 넘기는 버튼을 만들어보도록 하겠습니다. 보통 이런 버튼을 Navigation View라고 명칭 합니다. 예제 프로그램에서는 아래에 위치하게 하여 Bottom Navigation View라고도 보통 불립니다. 각각의 이미지는 인터넷에서 다운로드하여 res/drawable 폴더에 추가하여 적용하였습니다. 

    btm_navigation_main.xml 의 레이아웃 디자인

    해당 레이아웃 디자인에 대한 XML Code는 아래와 같습니다.

    파일명 : btm_navigation_main.xml

    <?xml version="1.0" encoding="utf-8"?>
    <LinearLayout
            xmlns:android="http://schemas.android.com/apk/res/android"
            android:layout_width="match_parent"
            android:layout_height="50dp"
            android:background="#ffffff"
            android:elevation="5dp"
            android:orientation="horizontal">
    
        <RelativeLayout
                android:id="@+id/xml_btmnv_btn_profile"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:layout_weight="1">
            <ImageView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_centerInParent="true"
                    android:src="@drawable/img_btm_profile" />
        </RelativeLayout>
    
        <RelativeLayout
                android:id="@+id/xml_btmnv_btn_friends"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:layout_weight="1">
            <ImageView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_centerInParent="true"
                    android:src="@drawable/img_btm_friends" />
        </RelativeLayout>
    
        <RelativeLayout
                android:id="@+id/xml_btmnv_btn_search"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:layout_weight="1">
            <ImageView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_centerInParent="true"
                    android:src="@drawable/img_btm_search" />
        </RelativeLayout>
    
        <RelativeLayout
                android:id="@+id/xml_btmnv_btn_chat"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:layout_weight="1">
            <ImageView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_centerInParent="true"
                    android:src="@drawable/img_btm_chat" />
        </RelativeLayout>
    
        <RelativeLayout
                android:id="@+id/xml_btmnv_btn_setting"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:layout_weight="1">
            <ImageView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_centerInParent="true"
                    android:src="@drawable/img_btm_setting" />
        </RelativeLayout>
    </LinearLayout>

     

     

    두 번째로는 Bottom Navigation View와 프래그먼트를 담아서 한 화면에서 보여주는 메인 액티비티 레이아웃 부분을 살펴보도록 하겠습니다. 위의 부분이 프래그먼트 부분을 담는 ViewPaper이고 아래 부분이 Bottom Navigation View를 보여주는 TabLayout 부분입니다.

    activity_main.xml 의 레이아웃 디자인

    해당 레이아웃 디자인에 대한 XML Code는 아래와 같습니다.

    파일명 : activity_main.xml

    <?xml version="1.0" encoding="utf-8"?>
    <RelativeLayout
            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">
    
        <androidx.viewpager.widget.ViewPager
                android:id="@+id/xml_main_viewpaper"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:layout_above="@+id/xml_main_tablayout">
        </androidx.viewpager.widget.ViewPager>
    
        <com.google.android.material.tabs.TabLayout
                android:id="@+id/xml_main_tablayout"
                android:background="#FFFFFF"
                android:elevation="5dp"
                app:tabIndicatorColor="#40D39F"
                android:layout_width="match_parent"
                android:layout_height="50dp"
                android:layout_alignParentBottom="true">
        </com.google.android.material.tabs.TabLayout>
    
    </RelativeLayout>

     

    2. 프래그먼트 ( Fragment ) 추가

    위에서 설명한 것처럼 프래그먼트는 ViewPaper에 보이는 페이지를 뜻합니다. 오늘은 그 페이지를 생성해서 디스플레이만 할 뿐 해당 프래그먼트 내부 수정은 없으므로 추가하는 방법만 알려드리도록 하겠습니다.

    위에 사진에서 보면, 먼저 저는 Fragment라는 Package를 만들어서 페이지를 다른 Kotlin 파일과 쉽게 분류가 되도록 했습니다. 이후 위의 사진과 같이 프래그먼트를 추가하시면 됩니다. 위의 사진에서 맨 마지막 < Fragment (Blank) >를 클릭하는 경우 아래와 같은 창이 나옵니다.

    이와 같은 방식으로 프래그먼트를 5개 생성을 했습니다. 이유는 예제 프로그램의 Bottom Navigation View 내부에 버튼이 5개가 있기 때문이죠. kt파일, xml파일이 각각 5개씩 생성이 됩니다. 제가 만든 프래그먼트의 kt파일명은 아래와 같습니다.

    1. FragmentMainProfile
    2. FragmentMainFriends
    3. FragmentMainSearch
    4. FragmentMainChat
    5. FragmentMainSetting

     

     

    3. 코틀린 소스 ( Kotlin Source Code ) 구성

    먼저 MainActivity.kt를 살펴보도록 하겠습니다.

    ...
    
    import androidx.appcompat.app.AppCompatActivity
    import android.os.Bundle
    import android.view.View
    import android.widget.RelativeLayout
    import com.rainman.ishida.let_us_date_firebase.Adapter.AdapterMainFragment
    import kotlinx.android.synthetic.main.activity_main.*
    
    class MainActivity : AppCompatActivity() {
    
        override fun onCreate(savedInstanceState: Bundle?) {
            super.onCreate(savedInstanceState)
            setContentView(R.layout.activity_main)
    
            configureBottomNavigation()
        }
    
        private fun configureBottomNavigation(){
            xml_main_viewpaper.adapter = AdapterMainFragment(supportFragmentManager, 5)
            xml_main_tablayout.setupWithViewPager(xml_main_viewpaper)
    
            val viewBtmNaviMain : View = this.layoutInflater.inflate(R.layout.btm_navigation_main, null, false)
    
            xml_main_tablayout.getTabAt(0)!!.customView = viewBtmNaviMain.findViewById(R.id.xml_btmnv_btn_profile)  as RelativeLayout
            xml_main_tablayout.getTabAt(1)!!.customView = viewBtmNaviMain.findViewById(R.id.xml_btmnv_btn_friends)  as RelativeLayout
            xml_main_tablayout.getTabAt(2)!!.customView = viewBtmNaviMain.findViewById(R.id.xml_btmnv_btn_search)   as RelativeLayout
            xml_main_tablayout.getTabAt(3)!!.customView = viewBtmNaviMain.findViewById(R.id.xml_btmnv_btn_chat)     as RelativeLayout
            xml_main_tablayout.getTabAt(4)!!.customView = viewBtmNaviMain.findViewById(R.id.xml_btmnv_btn_setting)  as RelativeLayout
        }
    }

    configureBottomNavigation 함수 내부에서 AdapterMainFragment라는 어댑터 클래스를 통해서 Bottom Navigation View 내부의 버튼과 ViewPaper 내부의 프래그먼트(페이지)가 연결되어 있는 것을 볼 수 있습니다.

     

    그렇다면 AdaptermainFragment.kt 내부를 살펴보도록 하겠습니다.

    ...
    
    import androidx.fragment.app.Fragment
    import androidx.fragment.app.FragmentManager
    import androidx.fragment.app.FragmentStatePagerAdapter
    import com.rainman.ishida.let_us_date_firebase.Fragment.*
    
    class AdapterMainFragment(fm : FragmentManager, private val fragmentCount : Int) : FragmentStatePagerAdapter(fm) {
        override fun getItem(position: Int) : Fragment {
            return when(position){
                0 -> FragmentMainProfile()
                1 -> FragmentMainFriends()
                2 -> FragmentMainSearch()
                3 -> FragmentMainChat()
                4 -> FragmentMainSetting()
                else -> FragmentMainProfile()
            }
        }
    
        override fun getCount(): Int = fragmentCount
    } 

    MainActivity.kt에서 버튼을 매핑한 순서와 어댑터 클래스 내부에 프래그먼트가 매핑되어 있는 순서가 같은 것을 보실 수 있습니다.

     

    이렇게 해서 프래그먼트 & Bottom Nagivation View를 사용한

    예제 프로그램을 구성해볼 수 있었습니다.

     

    오늘 글도 여러분께 많은 도움이 됐기를 희망합니다.

    감사합니다!

     

    반응형

    댓글

Designed by Tistory.