Archives
Recent Posts
«   2025/02   »
1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28
Today
Total
관리 메뉴

안드로이드 개발자의 창고

[41일차 Android] TabLayout(ViewPager2과 TabLayout 연동) 본문

Computer/Android

[41일차 Android] TabLayout(ViewPager2과 TabLayout 연동)

Wise-99 2023. 7. 4. 22:30

 

 

 

출처 : 안드로이드 앱스쿨 2기 윤재성 강사님 수업 PPT

 

 

 

📖 TabLayout

  • AppbarLayout에 TabBarLayout과 ViewPager를 통해 탭을 구성할 수 있다.

 

예제 코드

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<androidx.coordinatorlayout.widget.CoordinatorLayout 
    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"

    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <com.google.android.material.appbar.AppBarLayout
        android:id="@+id/appbar"
        android:layout_height="wrap_content"
        android:layout_width="match_parent">

        <androidx.appcompat.widget.Toolbar
            android:layout_height="?attr/actionBarSize"
            android:layout_width="match_parent"
            app:layout_scrollFlags="scroll|enterAlways">
        </androidx.appcompat.widget.Toolbar>

        <com.google.android.material.tabs.TabLayout
            android:id="@+id/tabs"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"

            app:tabMode="scrollable"/>
    </com.google.android.material.appbar.AppBarLayout>

    <androidx.core.widget.NestedScrollView
        android:layout_width="match_parent"
        android:layout_height="match_parent"

        app:layout_behavior
            ="com.google.android.material.appbar.AppBarLayout$ScrollingViewBehavior">

        <androidx.viewpager2.widget.ViewPager2
            android:id="@+id/pager2"
            android:layout_width="match_parent"
            android:layout_height="match_parent" />
    </androidx.core.widget.NestedScrollView>

</androidx.coordinatorlayout.widget.CoordinatorLayout>

 

 

 

MainActivity.kt

class MainActivity : AppCompatActivity() {

    lateinit var activityMainBinding: ActivityMainBinding

    // 탭에 표시할 이름
    val tabName = arrayOf(
        "탭1", "탭2", "탭3", "탭4", "탭5"
    )

    // 표시할 Fragment들을 담을 리스트
    val fragmentList = mutableListOf<Fragment>()

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        activityMainBinding = ActivityMainBinding.inflate(layoutInflater)
        setContentView(activityMainBinding.root)

        activityMainBinding.run {
            // 사용할 프래그먼트들을 생성하여 리스트에 추가
            fragmentList.add(Sub1Fragment())
            fragmentList.add(Sub2Fragment())
            fragmentList.add(Sub3Fragment())
            fragmentList.add(Sub4Fragment())
            fragmentList.add(Sub5Fragment())

            // Viewpager 어뎁터를 설정
            pager2.adapter = TabAdapterClass(this@MainActivity)

            // tab과 ViewPager2 연결
            val tabLayoutMediator = TabLayoutMediator(tabs, pager2)
            { tab: TabLayout.Tab, i: Int ->
                
                tab.text = tabName[i]
            }
            tabLayoutMediator.attach()
        }
    }

    // 어뎁터 클래스
    inner class TabAdapterClass(fragmentActivity: FragmentActivity) : FragmentStateAdapter(fragmentActivity){
        // 탭의 갯수
        override fun getItemCount(): Int {
            return fragmentList.size
        }

        // 탭 생성
        override fun createFragment(position: Int): Fragment {
            return fragmentList[position]
        }
    }
}

 

 

 

결과

  • 탭 제목 클릭이나 좌우 스크롤을 통해 탭 전환이 가능하다.